Require a javascript library inside Jade
Asked Answered
G

3

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?

Gizela answered 3/6, 2014 at 5:12 Comment(0)
E
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.

Earle answered 3/6, 2014 at 5:21 Comment(0)
C
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.

Cromer answered 3/6, 2014 at 5:18 Comment(3)
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.Schalles
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.Cromer
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.Schalles
R
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.

Rankin answered 22/11, 2018 at 22:18 Comment(1)
Note: 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.Gizela

© 2022 - 2024 — McMap. All rights reserved.