gpt4 book ai didi

node.js - 如何让 {{>partials} 与 Consolidate.js 和 Mustache 一起工作?

转载 作者:搜寻专家 更新时间:2023-10-31 23:10:10 25 4
gpt4 key购买 nike

当与 consolidate.js 一起使用时,我无法像 {{>my_partial}} 这样添加 mustache 阅读部分。我用类似这样的东西开始我的快速应用程序:

文件index.js:

var express = require('express'),
cons = require('consolidate');

app.configure(function(){

app.set( 'models', BACKEND + '/models' ); // Set the models directory
app.set( 'views', BACKEND + '/views' ); // Set the views directory
app.set( 'controllers', BACKEND + '/controllers' ); // Set the controllers dir


app.set( 'view engine', 'html' ); // Set Mustache as the templating engine
app.engine( 'html', cons.mustache );
app.engine( 'mustache', cons.mustache );

app.use( app.router ); // Set the router
app.use( '/public', express.static( BASEPATH + '/frontend/public' ) ); // set frontend/public to /public for users
app.use( '/js', express.static( BASEPATH + '/frontend/js' ) );
app.use( '/out', express.static( BASEPATH + '/out' ) ); // documentation path

// Set client side libraries here (Make them available to the public based on settings.json)
for(setting in SETTINGS.public) {
app.use( SETTINGS.public[setting], express.static(BASEPATH + SETTINGS.public[setting]) );
}

});

然后,在 Controller 的某处,我像这样使用渲染器:

function Blog(app, request, response){

var fs = require('fs'),
Blog = require( app.get('models') + '/blog' ),
model = new Blog(),
scripts = fs.readFileSync( VIEWS + '/m_scripts.mustache').toString() ;

model.List(function(data){

response.render('layout',
{
title : 'My Blog',
body : 'Hello Mustache World',
list : data.rows,
cache : false,
partials : {
m_scripts : partialStr
}
}
);

});

};


exports.list = Blog;

m_scripts.mustache 有:

<script data-src="ergierjgoejoij"></script>

布局模板渲染得很好,参数传递也很好,部分 m_scripts 与 readFileSync().toString() 传递的文本一起传递得很好,但 HTML 内容被编码并变得无用。

我的问题是,有没有一种方法我可以只放入 layout.mustache {{>m_scripts}} 并且 mustache 理解自动加载 m_scripts.mustache 而无需将其传递给 render()。如果不是,我错过了什么?

最佳答案

事实证明,目前 consolidate.js 不支持 partials。有一个解决此问题的拉取请求,但尚未合并:https://github.com/simov/consolidate.js

我最终改用了那个 fork :

1) npm 卸载合并

2) npm 安装 simov/consolidate.js

npm install simov/consolidate.js 将安装该分支版本。然后我可以执行以下操作:

/**
* @module Blog Controller
*/
function Blog(app, request, response){

var Blog = require( app.get('models') + '/blog' ),
model = new Blog();

model.List(function(data){

response.render('layout',
{
title : 'My Blog',
body : 'Hello Mustache World',
list : data.rows,
cache : false
,partials : {
m_scripts : './backend/views/m_scripts.html'
}
}
);

});

};


exports.list = Blog;

比我想象的简单多了。您改为将路径传递给您的部分,然后您可以在 layout.html 上使用 {{>m_scripts}}

不过,不确定是否有办法做到这一点,默认情况下,在 views 文件夹或其他文件夹中查找 {{>m_scripts}}。那会很整洁。

关于node.js - 如何让 {{>partials} 与 Consolidate.js 和 Mustache 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14005106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com