简体   繁体   English

将变量传递给没有Express的Jade

[英]Pass variables to Jade without Express

Quick question about the Jade template engine: 关于Jade模板引擎的快速问题:

  • How can you pass node.js variables to a .jade template when you're not using express.js ? 如果不使用express.js如何将node.js变量传递给.jade模板?

I'm trying to make a small website that doesn't use express, just so that I can understand how everything works. 我正在尝试创建一个不使用express的小型网站,这样我才能理解一切是如何运作的。

Also, are there tutorials or articles about the use of Jade and node.js without express? 另外,是否有关于使用Jade和node.js而没有表达的教程或文章?

var jade = require('jade');
jade.renderFile('tpl.jade', { hello: 'world' }, function(err, html) {
        console.log(err);
        console.log(html);
});

tpl.jade: tpl.jade:

html
  body
    h1 #{hello}

Vadim 's answer is nice, but old. 瓦迪姆的回答很好,但很老。 It uses a different syntax to declare Jade variables then what is used currently at Jade's official tutorial . 它使用不同的语法来声明Jade变量,然后在Jade的官方教程中使用它 Also, it does not show how to use Jade options . 此外,它没有显示如何使用Jade选项

Simple Example 简单的例子

index.jade index.jade

doctype html
html
  head
    title= pageTitle
  body
    h1= greetings

In this example, variables are pageTitle and greetings . 在此示例中,变量是pageTitlegreetings

app.js app.js

var jade = require('jade');

var locals = {
  pageTitle : 'My Page',
  greetings : 'Hello World!'
};

jade.renderFile('index.jade', locals, function(err, html) {
  console.log(html);
});

Output: 输出:

<!DOCTYPE html><html><head><title>My Page</title></head><body><h1>Hello World!</h1></body></html>


Using Jade Options 使用Jade选项

The previous example outputs the HTML without pretty print. 上一个示例输出的HTML没有漂亮的打印。 That's not a problem, but Jade has an option that outputs pretty printed HTML. 这不是问题,但Jade有一个选项可以输出漂亮的HTML。 You can see the full list of options here . 您可以在此处查看完整的选项列表。

Jade's official tutorial doesn't teach how to use options when you also have variables in your template. 当你的模板中也有变量时,Jade的官方教程没有教导如何使用选项。 Jade's GitHub page tries to teach, but is incomplete. Jade的GitHub页面试图教,但不完整。 It uses: 它用:

jade.renderFile('filename.jade', merge(options, locals));

As merge is an undefined function, you have to define it. 由于merge是一个未定义的函数,您必须定义它。 This function will merge two JSON objects. 此函数将合并两个JSON对象。

app.js app.js

var jade = require('jade');

function merge(obj1, obj2) {
  var result = {};

  for(var key in obj1) 
    result[key] = obj1[key];

  for(var key in obj2) 
    result[key] = obj2[key];

  return result;
}

var options = {
  pretty : true
};

var locals = {
  pageTitle : 'My Page',
  greetings : 'Hello World!'
};

jade.renderFile('index.jade', merge(options, locals), function(err, html) {    
  console.log(html);
});

Output: 输出:

<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM