从现有文件加载模板 [英] Load templates from existing file

查看:80
本文介绍了从现有文件加载模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的NodeJS应用程序中使用 Handlebars 作为模板引擎。

I'm using Handlebars in my NodeJS application as my templating engine.

我的模板在视图文件夹中,如下所示:

I've put all my templates in a views folder like so :

-
  - /controllers
  - /views
    - index.html
  - server.js

这是我的代码,当用户访问给定的URL时(使用 express 进行路由),呈现模板:

Here's my code to render the template when the user access a given URL (using express for routing) :

app.get("/", function(req, res){

    var template = handlebars.compile("views/index.html");
    var data = {"name": "Charles"};
    var result = template(data);

    res.send(result);
});

我试图从文件中渲染模板,但它不起作用。这是浏览器在访问 / URL时直接输出的内容:

I'm trying to render a template from a file, but it's not working. This is what the browser outputs directly when I'm accessing the / URL :

views/index.html

这很有道理,因为它将给定的param解释为一个字符串直接而不是作为外部模板的路径。

That makes sense, since it's interpreting the given param as a string directly and not as a path to an external template.

如何将我的模板文件(本例中是 views / index.html 中的一个)加载到变量,以便我可以渲染模板?

How can I load my template file (in this case the one in views/index.html to a variable, so that I can then render the template?

我发现的唯一例子是将所有模板存储在一个文件中并通过AJAX加载它们,但所有这些例子都来自前端的把手,而不是当与Node一起使用时。

The only examples I found were storing all the templates in a file and loading them via AJAX, but all these examples were from "front-end" handlebars and not when using it with Node.

有可能实现我想要的吗?我查看了文档,但很难找到好的信息对于带有NodeJS的handlebars。

Is it possible to achieve what I want? I looked at the documentation but it's hard to find good infos for handlebars with NodeJS.

推荐答案

从你的描述来看,这听起来像你希望把手作为视图引擎和动态视图。不需要手动执行此操作,这里是一个示例(使用快速处理栏):

From your description, it sounds like you want handlebars as view engine, with dynamic views. You don't need to do this manually, here is an example (using express-handlebars):

var handlebars = require('express-handlebars');

app.engine('.html', handlebars({layout: false, extname: '.html'}));
app.set('view engine', '.html');

app.get("/:view", function(req, res){
  var view = req.params.view;
  res.render(view, { "name": "Charles" });  // Whatever data you want
});

这篇关于从现有文件加载模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆