0

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?

Community
  • 1
  • 1
laggingreflex
  • 32,948
  • 35
  • 141
  • 196

3 Answers3

4
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.

Ryan
  • 14,392
  • 8
  • 62
  • 102
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.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • The whole "locals" deal is quite confusing for me (pretty new to the node world). Is this a Jade, Node, or JS thing? Including some examples in your answer would be quite helpful. – Isaac Gregson Sep 02 '14 at 06:16
  • locals is both a jade thing and an express thing. Templates take a string with some placeholders and replace the placeholders with real data values. The real data values are called the "locals". See true's answer for an example. – Peter Lyons Sep 02 '14 at 16:24
  • Thanks for the insight, Peter. Seems the main thing that's causing me confusion is entering the Node world without entering the Express world. I'm using Gulp for a custom static bulid system... posted [a related question here](http://stackoverflow.com/questions/25617795/how-to-use-markdown-in-yaml-data-file-with-jade). – Isaac Gregson Sep 02 '14 at 18:12
0

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.

McB
  • 1,082
  • 1
  • 18
  • 36
  • Note: [require](https://nodejs.org/api/modules.html#modules_require) will only resolve paths against the original file it was passed to. This wouldn't matter when using libraries that are in node_modules (like `moment`) but relative paths (like `./x`, `../xx`) might not work if the jade file using the passed `require` is in a different directory. – laggingreflex Nov 22 '18 at 22:58