go 模板中一个if判断的问题,明明是true却走的false的分支。

angilent · 2017-09-08 09:40:16 · 1867 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-09-08 09:40:16 的主题,其中的信息可能已经有所发展或是发生改变。

在学Hugo CMS,其中有一段模板是这样的

    <article class="6u 12u$(xsmall) work-item {{ $.Site.Params.Use_out_img }} {{  $.Site.Params.OutImgLink }}">
        {{ if .Site.Params.Use_out_img }}
        <a href="{{ $.Site.BaseURL }}images/{{ .image }}?33" class="image fit thumb"><img src="{{ $.Site.BaseURL }}images/{{ .thumb }}" alt="" /></a>
        {{ end }} 
        {{ if not .Site.Params.Use_out_img }}
        <a href="{{ $.Site.Params.OutImgLink }}{{ .image }}" class="image fit thumb"><img src="{{ $.Site.Params.OutImgLink }}{{ .thumb }}" alt="" /></a>
        {{ end }}
        <h3>{{ .title | markdownify }}</h3>
        <p>{{ .description | markdownify }}</p>
    </article>

页面逻辑很简单: 判断 .Site.Params.Use_out_img 是否被设置为true,如果是true则走第一个分支,否则走第二的分支。

页面上用 {{ $.Site.Params.Use_out_img }} 打出的字符是 true, 但代码却走的是后一段。 {{ if not .Site.Params.Use_out_img }}

这个值是在配置文件中设定的: [params]

# To provide some metadata for search engines feel free to add a few
    # information about you and your website.
# Add read time estimates in the format "X min read"
show_read_time = true

# use image server 
use_out_img = true

之前没用学过go,目前只是照猫画虎改模板。 求高人指点。 谢过先~


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1867 次点击  
加入收藏 微博
5 回复  |  直到 2017-09-11 08:28:13
channel
channel · #1 · 8年之前

给下代码链接吧。

angilent
angilent · #2 · 8年之前
channel
channel · #3 · 8年之前

{{ if .Site.Params.Use_out_img }} 不应该是 {{ if $.Site.Params.Use_out_img }} 吗?

angilent
angilent · #4 · 8年之前

@channel 果然是这个原因。 万分感谢! 是因为在range 里,所以 . 所代表的上下文环境就变了。 但是加$的意识是回到最外层的上下文环境??

channel
channel · #5 · 8年之前

回到根上下文

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传