这是我的用例
我有一个文件可以将各个部分(holy-grail.njs)拉到一起,然后通过我想要的实际页面(single.njs)进行扩展。问题是实际页面模板会忽略包含文件中定义的块。您可以看到扩展侧边栏文字未显示在屏幕截图<p>Here is some additional content for the sidebar extended in</p>
只是为了笑容,我把那个块代码从sidebar.njs移到了holy-grail.njs,是的,它被single.njs扩展,所以确实如我所怀疑的那样。
是一个错误?,一个非特色?如何解决问题?或者翡翠会做我想要的吗?我认为“包含”文件只是包含在进一步处理之前,但是它们可能会被处理然后包括在内吗?我无法做到这一点,我整个模板组件/部分组织然后扩展/自定义内容的整个方式将是不行的。
三年前问了同样的问题,没有人回答 Blocks in included files not being filled by extended templatessingle.njs
{% extends "layouts/holy-grail.njs" %}
{% block sidebar %}
<p>Here is some additional content for the sidebar extended in</p>
{% endblock %}
{% block article %}
{% raw %}
{{ Hugo code here to grab the article title and content }}
{% endraw %}
{% endblock %}
圣-grail.njs
{% set reg = "regions/" %}
{% set cmp = "components/" %}
{% include "regions/head.njs" %}
<body class='page'>
{% include reg + "header.njs" %}
<div class="rollover-wrapper">
{% include reg + "topbar.njs" %}
<main>
{% include reg + "sidebar.njs" %}
<section id="content">
{% block article %}
{# This is where one melds in article content #}
{% endblock %}
</section>
</main>
{% include reg + "footer.njs" %}
</div>
{% include cmp + "javascripts.njs" %}
</body>
sidebar.njs
<aside id="sidebar" class="sidebar">
<p> some sidebar content set in the sidebar.njs file </p>
{% block sidebar %}
{# This is where one melds in more sidebar content #}
{% endblock %}
</aside>
答案 0 :(得分:1)
这是来自Nunjucks的一位维护者
您的猜测是正确的:包括在更高级别的操作&#34;比 模板继承。因此,包含的模板可以包含块,并且可以 拥有自己的&#34;扩展&#34;标签和完全独立的模板 继承层次结构,但它的块不以任何方式与之交互 包含模板的继承层次结构的块。
所以我提出的解决方案是使用另一个工具(gulp插件)来预先组装部分,然后通过像这样的nunjucks来运行它们。
N.B我的预处理器文件使用扩展名* .pnjs并输出到相应的* .njs文件,然后在single.njs中处理/扩展。
var merge = require('gulp-file-include')
var rename = require("gulp-rename");
gulp.task('html:pre', function() {
gulp.src(['assets/html/nunjucks/layouts/*.pnjs'])
.pipe(merge({
prefix: '@@',
basepath: 'assets/html/nunjucks'
}))
.pipe(rename({extname: ".njs"}))
.pipe(gulp.dest('assets/html/nunjucks/layouts/'));
});
var nunjucks = require('gulp-nunjucks-render');
gulp.task('html:njs',['html:pre'], function() {
gulp.src('assets/html/nunjucks/*.njs')
.pipe(nunjucks({ path: ['assets/html/nunjucks'] // String or Array
}))
.on('error', console.log)
.pipe(gulp.dest('./builds/dev/'));
});
然后您必须将包含语法更改为gulp-file-include支持的语法
像这样。@@include('regions/head.njs')
<body class='page'>
@@include('regions/header.njs')
<div class="rollover-wrapper">
@@include('regions/topbar.njs')
<main>
@@include('regions/sidebar.njs')
<section id="content">
{% block article %}
{# This is where one melds in article content #}
{% endblock %}
</section>
</main>
@@include('regions/footer.njs')
</div>
@@include('components/javascripts.njs')
</body>