Grav - 从模板中的页面检索特定项目

Grav - Retrieving specific items from page in template

我在 Grav 中的页面结构如下:

# Title
## Subtitle
### Subsubtitle

页面结构始终相同,只有这三个项目。

如何在 Twig 模板中分别检索每个项目 (Title/Subtitle/Subsubtitle)?

然后,twig 模板将执行以下操作:

<p> You typed {{ page.whatever_retrieves_the_title_# }} as title, then {{ page.whatever_retrieves_the_subtitle_## }} as subtitle and finally {{ page.whatever_retrieves_the_subsubtitle_### }} as subsubtitle</p>

如果不是上面的结构我有:

- Title
- Subtitle
- Subsubtitle

objective是用户只添加了三个项目的结构,twig 模板使用每个项目来显示更复杂的布局。

这是 Markdown,对吧?

# Title
## Subtitle
### Subsubtitle

您可以使用 {{ page.content }} 在 Twig 中获取页面 Markdown 的 HTML 版本,如 Grav's documentation 中所述。所以你应该得到这样的东西:

<h1>Title</h1>
<h2>Subtitle</h2>
<h3>Subsubtitle</h3>

您可以使用 splitraw 过滤器来提取这些标签的内容。我还使用了 default 过滤器,这样如果标签内容的提取失败就不会出现错误:

Title is:
{{ page.content|split('<h1>')[1]|default|raw|split('</h1>')[0] }}

Subtitle is:
{{ page.content|split('<h2>')[1]|default|raw|split('</h2>')[0] }}

Subsubtitle is:
{{ page.content|split('<h3>')[1]|default|raw|split('</h3>')[0] }}

或者因为 Grav 似乎提供了一个 regex_replace filter,你也可以使用它:

Title is:
{{ page.content|regex_replace('~.*<h1>(.*)</h1>.*~s', '') }}

Subtitle is:
{{ page.content|regex_replace('~.*<h2>(.*)</h2>.*~s', '') }}

Subsubtitle is:
{{ page.content|regex_replace('~.*<h3>(.*)</h3>.*~s', '') }}

如果你有这个:

- Title
- Subtitle
- Subsubtitle

您可以再次使用 splitdefaultraw 过滤器:

Title is:
{{ page.content|split('<li>')[1]|default|raw|split('</li>')[0] }}

Subtitle is:
{{ page.content|split('<li>')[2]|default|raw|split('</li>')[0] }}

Subsubtitle is:
{{ page.content|split('<li>')[3]|default|raw|split('</li>')[0] }}

不是很漂亮。 :-) 如果标题可以包含 HTML(例如 ## Hello **world**!<h2>Hello <strong>world</strong>!</h2>)或特殊字符,您可能需要将 |raw 附加到已经很长的魔法咒语。

其他人提供了很好的降价操作解决方案。但是,您可以使用重力功能并提供您自己的蓝图,并让您的用户填写一些字段。

假设这是一个使用模板 blog_article.html.twig 的页面,因此您可以在 user/themes/yourtheme/blueprints 中创建一个名为 blog_article.yaml 的文件并用以下蓝图填充它:

title: Blog_Article
'@extends':
    type: default
    context: blueprints://pages

form:
  fields:
    tabs:
      fields:
        content:
          fields:
            header.mytitle:
              type: text
              label: My Label
            header.mysubtitle:
              type: text
              label: Type Subtitle
            header.mysubsubtitle
              type: text
              label: Type subsubtitle

现在,如果您尝试从管理员编辑您的页面,您将看到页面媒体下添加了三个新字段。

然后您可以使用以下分支在模板中显示这些字段:

{{ page.header.mytitle }} 
{{ page.header.mysubtitle }}
{{ page.header.mysubsubtitle }}

希望对您有所帮助