0

我使用 nunjucks (gulp) 作为模板语言,我想构建一个动态页面模板。

这是我的 Json:

"pages": [
    {
        uname: "Welcome",
        title: "Page 1 Headline"
    },
    {
        uname: "About",
        title: "Page 2 Headline"
    }
]

目前我为每个页面都有一个静态页面(html)模板:

{% extends "layout.html" %}
{% set active_page = "Welcome" %} //<- This needs to be dynamicly
{% block content %}

<h1>{{ page[0].title }}</h1> //<- This needs to be dynamicly

我的第一个想法是读取 url 参数,但我无法以这种方式解决它。

有什么建议么?

4

3 回答 3

0

如果您希望从 data.json 文件中传递数据

  1. 首先,您需要使用某种方式在数据文件本身中指定页面名称。
  2. 然后您必须在 nunjucks 页面中将页面名称设置为变量。
  3. 现在您可以使用此变量名称来获取与您正在处理的页面相关的数据。

数据.json

{
    "pages": {
        "welcome": {
           "uname": "Welcome",
           "title": "Page 1 Headline"
        },
        "about": {
           "uname": "About",
           "title": "Page 2 Headline"
        },
    }
}

索引.njk

{% set pageName = 'welcome' %}
{% extends "layout.html" %}
{% set active_page = "Welcome" %}
{% block content %}

<h1>{{ page[pageName].title }}</h1>
于 2019-05-13T15:50:20.807 回答
0

解决方案很简单!

需要这样做:

索引.njk

<!-- set title !!! -->
{% set title = 'home page' %} <!-- set title !!! -->
{% extends "layout.njk" %}

{% block header %} {% include "parts/header.njk" %} {% endblock %}
{% block main %}
<main class="main">
    <!-- content -->
</main>
{% endblock %}
{% block footer %} {% include "parts/footer.njk" %} {% endblock %}

page1.njk

<!-- set title !!! -->
{% set title = 'page1' %}
{% extends "layout.njk" %}

{% block header %} {% include "parts/header.njk" %} {% endblock %}
{% block main %}
<main class="main">
    <!-- content -->
</main>
{% endblock %}
{% block footer %} {% include "parts/footer.njk" %} {% endblock %}

布局.njk

<!-- layout.njk -->

<html lang="en">
    <head>
      <!-- here is the compiled title -->
      <title>{{ title }}</title>
      <link rel="stylesheet" href="styles/style.css">
    </head>
    <body class="page">
        {% block header %}{% endblock %}
        {% block main %}{% endblock %}
        {% block footer %}{% endblock %}
    </body>
 </html>
于 2019-01-10T07:55:44.033 回答
-1
{% macro inc(file, folder) %}
    {% if folder %}
        {% set folderPATH = folder %}
    {% else %}
        {% set folderPATH = file %}
    {% endif %}
    {% set path = folderPATH + "/" + file + ".njk" %}
    {% include path %}
{% endmacro %}

{{ inc("menu") }} // {% include "menu/menu.njk" %}
{{ inc("content") }} // {% include "content/content.njk" %}
于 2017-11-02T10:54:58.757 回答