dongzhi7641 2017-08-21 00:38
浏览 68

从Go HTML模板中的父对象访问变量

I have recursive go html templates for showing replies to a post, the top parent object contains a field called Random and a field called Replies, I recurse over the replies, which don't have the Random field, but I want to use that same Random field in each reply.

When I try this it only goes two replies deep (I assume because $ only references the parent object and not the "top" parent object.

EDIT: More code. thread is the original object passed to the template, thread.Replies are looped over recursively, but don't contain the thread.Random string. I want to make the thread.Random string available globally to all the children without restructuring the structs.

type thread struct {
    Random string
    Body string
    Title string
    Replies []*reply
}

type reply struct {
    Body string
    Title string
    Replies []*reply
}

Template:

<html>                                                    
  <body>                                                  
  <div id="posts">
    <p>.Title</p>
    <p>.Body</p>                                        
    {{define "replies"}}                                  
    <ul>                                                  
      {{ range $key, $value := .Replies }}               
        <p>$value.Title</p>                               
        <p>$value.Body</p>                                
        <p>$.Random</p>                                   
        {{template "replies" . }}                         
        </li>                                             
      {{end}}                                             
    </ul>                                                 
    {{end}}                                               

  <div id="posts">                                        
    <div class="replyPost">{{ template "replies" .}}</div>
  </div>                                                  
  </body>                                                 
</html>                                                   
  • 写回答

1条回答 默认 最新

  • dongzhanlian6289 2017-08-21 05:21
    关注

    Whatever you want to access in a template must be passed to it. There is no such thing as "this struct originally was a field of some other struct and I want to magically access this other struct".

    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测