【问题标题】:Hugo layouts split h3 content to divHugo 布局将 h3 内容拆分为 div
【发布时间】:2019-01-29 19:12:09
【问题描述】:

我想知道如何通过以下方式修改简单 test.md 文件的内容以生成带有 hugo 的 .html - 每个 h3 (###) 和前面的所有代码都放入,直到下一个 h3。简单来说,我想将每个 h3 部分拆分为单独的选项卡,标题与 h3 标签相同。

test.md 文件如下所示:

---
title: "Some title"
layout: test
---


## Title

### some content
lorem ipsum 1

### some content 2
lorem ipsum 2

### some content 3
lorem ipsum 3

所需的 hugo 输出如下所示:

<h2 id="title">Title</h1>
<div class="tabs">
  <div class="tab" id="some content">
    <h3 id="some-content">some content</h2>
    <p>lorem ipsum 1</p>
  </div>
  <div class="tab" id="some content">
    <h3 id="some-content-2">some content 2</h2>
    <p>lorem ipsum 2</p>
  </div>
  <div class="tab" id="some content">
    <h3 id="some-content-3">some content 3</h2>
    <p>lorem ipsum 3</p>
  </div>
</div>

如果可能的话,我想使用 Hugo 模板创建它,但也可以接受一些 javascript 技巧。感谢您提供任何线索。

【问题讨论】:

    标签: javascript hugo


    【解决方案1】:

    我有一个类似的功能要实现(只有 Hugo,没有 javascript),我必须在我的主题中定义一个 Hugo partial template

    themes/mytheme/layouts/partials/boxtext.html:

    {{ $paragraphs := split .Content "<h2 " }}
    
    {{ range $index, $p := $paragraphs }}
        {{ $pp := trim $p " \n" }}
        {{ if (eq $index 0) }}
            {{ printf "%s\n" $pp | safeHTML }}
        {{ end }}
        {{ if and (ne $pp "") (gt $index 0) }}
        <div class="boxtext">
            {{ printf "<h2 %s\n" $pp | safeHTML }}
        </div>
        {{ end }}
    {{end}}
    

    (这不是要按照您的意愿执行相同的输出:根据您的情况调整它,以split .Content "&lt;h3 " 开头而不是h2!)

    实际上,为了确定是否没有生成额外的行并保持紧凑,我不得不将其重写为:

    {{ $paragraphs := split .Content "<h2 " }}{{ range $index, $p := $paragraphs }}{{ $pp := trim $p " \n" }}{{ if (eq $index 0) }}{{ printf "%s\n" $pp | safeHTML }}{{ end }}{{ if and (ne $pp "") (gt $index 0) }}    <div class="boxtext">
            {{ printf "<h2 %s\n" $pp | safeHTML }}
        </div>{{ end }}{{end}}
    

    然后我的single.html 模板页面,我网站的相关部分可以包装生成的 HTML 代码:{{ partial "boxtext.html" . }}

    如:

    > cat "themes/mytheme/layouts/mysection/single.html"
    {{ define "main" }}
    
    <body id="id1">
        <div id="top">
            <ul class="menu">
            </ul>
        </div>
        <div>
            <div id="header">
                <h1>{{.Title}}</h1>
            </div>
        </div>
        <div>{{ range .Resources }}{{ if .RelPermalink }}
          <li>azza2<a href="{{ .RelPermalink }}">{{ .ResourceType | title }}</a></li>{{ else }}
          <li>{{ .ResourceType | title }} (no link, only embedded in page)</li>{{ end }}{{ end }}
        </div>
        {{ partial "boxtext.html" . }}
    </body>
    

    【讨论】:

    • 我也有类似的问题。我想 - 只有一个子页面 - 将我的内容分成两部分并在其间插入一些 javascript 计算器。我设法将计算器插入到底部或 {{.Content}} 之前,但不在两者之间。帮助表示赞赏! :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多