【问题标题】:Calling variables inside Hugo partial在 Hugo 局部调用变量
【发布时间】:2022-01-30 04:23:41
【问题描述】:

我在 Hugo 的部分代码中使用了这段代码来将上下文传递给它。

{{- $ctx := . -}}
    {{- $curPage := .page -}}
    {{- $otherVar := .otherVar -}}
    {{- with $curPage -}}
     {{ $section := .CurrentSection }}
    {{ if .IsHome }}
    <span class="post-section"><a href="{{ $section.Permalink }}" target="_blank">{{ $section.Title }}</a></span>
    {{ else }}
    <a href="{{  $section.Permalink }}"> {{  $section.Title }}</a>
    {{ end }}
    {{- end -}}

然后我将{{- $curPage := . -}} 添加到我希望部分显示的模板顶部,然后将部分调用为{{ partial "partial-name.html" (dict "page" $curPage "otherVar" .) }}。但是,该内容在主页上返回 nil,而它在站点范围内的其他任何地方都可以使用。谁能看看我的代码并告诉我哪里出错了?

【问题讨论】:

    标签: go hugo hugo-content-organization


    【解决方案1】:

    抱歉 - 没有看到你的 with 声明。

    所以 {{- $curPage := .page -}}

    是一个错字。

    .页面

    在本地 - 最新版本的 hugo 上测试。

    另请注意 - 我认为主页没有部分,因此您的跨度将输出很少,因为大多数当前部分或相关部分将不返回任何内容。

    【讨论】:

    • 它返回了一个error execute of template failed: template: partials/-partial-name.html:8:6: executing "partials/-partial-name.html" at &lt;$this&gt;: can't give argument to non-function $this
    • 见上文。经过测试。
    • .Page 返回空白,但我认为您在当前部分问题中是正确的。但似乎 Hugo 对嵌套部分的支持在变量方面非常有限。我在代码的.IsHome 内的条件中插入了一个随机链接和标题,它出现了。我只是不知道如何在主页上调用嵌套部分链接和标题。
    • 我建议你再写一个新问题......你到底遇到了什么并关闭这个......另请注意:如果 .Page 返回空白,则 .page 不是变量还有其他问题。
    【解决方案2】:

    既然你这样调用部分:

    {{ partial "partial-name.html" (dict "page" $curPage "otherVar" .) }}
                                                         ^^^^^^^^^^^^
                                                            Notice
    

    点 (.) 包含在 .otherVar 中。要确定您是否在主页上,请在 partial-name.html 的顶部使用类似这样的简单内容:

    {{ if .otherVar.IsHome }}
      <pre>Debugging: YES .IsHome</pre>
    {{ else }}
      <pre>Debugging: NOT .IsHome</pre>
    {{ end }}
    

    用上面的 GO HTML 片段测试后,你可以更新上面的原始代码。

    提示:在 Hugo 世界中,通常使用 "context""ctx""page""Page" 而不是 "otherVar" 作为包含点的字典键的名称。有关此问题的讨论,请参阅 Hugo 讨论组中的 Naming convention for page context (within a dictionary) when calling partial: seeking opinions

    另一个提示:有一些与区分大小写有关的 Hugo 怪事,所以无论如何我都不会使用 "otherVar"。而是使用"othervar""context" 或任何全小写且没有空格的名称。我这样做是因为我花了很多时间来处理区分大小写的 Hugo 问题。

    【讨论】:

    • 它返回错误can't give argument to non-function .context(将 othervar 更改为上下文)
    • 您是否将我建议的 5 行调试代码放在了partial-name.html 的顶部?如果将其放在顶部下方的某个位置,则点 (.) 可能已更改。有关这方面的更多帮助,请显示您的所有代码,因为我只是在猜测可能会发生什么。
    • 我做到了。它显示了调用部分的任何地方。我认为冲突是 .CurrentSection 在主页上返回 nil。
    猜你喜欢
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    相关资源
    最近更新 更多