我正在尝试了解Nunjucks模板的语言。
要生成 HTML,我使用 Gulp + 插件 gulp-nunjucks-render。
面临一个问题:我无法理解如何实现生成meta标签的title和description。
项目文件结构:
project
|
| -> dist > index.html (compiled)
| page1.html (compiled)
| page2.html (compiled)
|
|
| -> src
|-> pages -> index.njk (home page)
| page1.njk (page 1)
| page2.njk (page 2)
|
|-> templates
| |-> layout.njk
| |
| |-> parts -> header.njk
| footer.njk
|
|-> styles -> style.css
| style.min.css
|
|-> data.json
布局.njk
<!-- layout.njk -->
<html lang="en">
<head>
<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>
我连接到每个页面如下:
{% extends "layout.njk" %}
索引.njk
{% 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
{% extends "layout.njk" %}
{% block header %} {% include "parts/header.njk" %} {% endblock %}
{% block main %}
<main class="main">
<!-- content page1 -->
</main>
{% endblock %}
{% block footer %} {% include "parts/footer.njk" %} {% endblock %}
page2.njk
{% extends "layout.njk" %}
{% block header %} {% include "parts/header.njk" %} {% endblock %}
{% block main %}
<main class="main">
<!-- content page1 -->
</main>
{% endblock %}
{% block footer %} {% include "parts/footer.njk" %} {% endblock %}
我在文档中找不到任何标题输出示例,所以我在这里看到的最有趣的方式。
例如,从文件 .JSON 中获取标题和描述
数据.json
"pages": [
{
title: "Hompage"
description: "This is the home page"
},
{
title: "Page1"
description: "This is page 1"
}
{
title: "Page2"
description: "This is page 2"
}
]
gulpfile.js
const gulp = require('gulp');
const nunjucksRender = require('gulp-nunjucks-render');
const data = require('gulp-data');
gulp.task('nunjucks', function() {
return gulp.src('src/pages/**/*.njk')
.pipe(data(function() {
return require('./src/data.json')
}))
.pipe(nunjucksRender({
path: ['src/templates']
}))
.pipe(gulp.dest('docs'))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('watch', function(cb) {
gulp.parallel(
'nunjucks',
)(cb);
gulp.watch('src/**/*.njk', gulp.series('nunjucks'));
});
gulp.task('default', gulp.series('watch'));
我不知道如何从 json 中提取数据。请提出解决方案。