[英]Nunjucks dynamic page template
i'm using nunjucks (gulp) as templating language and i want to build a dynamic page template. 我正在使用nunjucks(gulp)作为模板语言,并且我想构建一个动态页面模板。
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: 目前我每个页面都有一个静态页面(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
My first thought was to read the url parameters but i couldn't solve it in this way. 我的第一个念头是读取url参数,但我无法以这种方式解决它。
Any suggestions? 有什么建议么?
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 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
<!-- 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>
If you are hoping to pass the data from data.json file 如果您希望传递data.json文件中的数据
data.json 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>
{% 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" %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.