Nunjucks dynamic page template

只愿长相守 提交于 2019-12-23 04:32:33

问题


i'm using nunjucks (gulp) as templating language and i want to build a dynamic page template.

This is my Json:

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

Currently i have a static page (html) template for each page:

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

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

My first thought was to read the url parameters but i couldn't solve it in this way.

Any suggestions?


回答1:


The solution was simple!

Need to do this:

index.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 %}

layout.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>



回答2:


If you are hoping to pass the data from data.json file

  1. first you need to use someway to specify the page name in the data file itself.
  2. Then you have to set the page name as a variable in the nunjucks page.
  3. Now you can use this variable name to get the data relevant to the page you are working in.

data.json

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

index.njk

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

<h1>{{ page[pageName].title }}</h1>



回答3:


{% 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" %}


来源:https://stackoverflow.com/questions/45439991/nunjucks-dynamic-page-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!