I'm trying to understand the language of Nunjucks templates.
To generate HTML I use Gulp + plugin gulp-nunjucks-render.
Faced a problem: I can not understand how to implement the generation of meta tags title and description.
Project file structure:
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
layout.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>
Which I connect to each page as follows:
{% extends "layout.njk" %}
index.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 %}
I couldn't find any examples of title output in the documentation, so the most an interesting way to I saw here.
For example, get the title and description from a file .JSON
data.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'));
I don't know how to extract data from json. Please advise a solution.
When you use
extends
, you should redefine block to override it