Require a javascript library inside Jade

你说的曾经没有我的故事 提交于 2019-12-23 06:57:36

问题


How do I require a library so that it works inside Jade.

Like if I want to be able to use CircularJSON in Jade

script var object = #{CircularJSON.stringify(object)}

I would basically need to define the function from that library into Jade

- var CircularJSON = function(e,t){function l(e,t,o){var u=[],...//whole function

which would be impractical and possibly impossible for much more complex libraries.

Is there a way to somehow simply require it instead?


回答1:


var myLib = require('../mylib');
response.render("index.jade", {
  lib  :  myLib
});

index.jade now has the myLib object. Now just use as you would anywhere else.




回答2:


Just require it in node and pass it to the template in the locals. locals can include functions as well entire modules, objects and scalar data.




回答3:


I like to take an approach similar to Peter Lyons and Zhifeng Hu (in another post), but instead of requiring everything into locals, I just require "require", then I can pull things in as needed in my templates.

app.use((req, res, next) => { res.locals.require = require; next() })

and then in Jade/Pug

- const moment = require('moment')
div Created at: #{moment(data.createdAt).fromNow()}

Basically the same thing, but I can keep the require code in the template where it's used.



来源:https://stackoverflow.com/questions/24007559/require-a-javascript-library-inside-jade

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!