Is there a way to include unbuffered javascript so multiple files can reuse the same functions, variables, etc.?
Example
- const viewbox = { x: 5000, y: 5000 };
Now I want to reuse this code across multiple files. Any ways to this?
Work-around:
This is possible in a rather unclean way: Create an pug file empty.pug (holding nothing, or a comment explaining why there is an empty file lying around that directory; if the empty strategy does not work, you can add a stub mixin in empty.pug just to please the compiler). Include that empty template in the pug template where you want to hold your JS code source, like this:
include empty
- function foo() { return "bar"; }
Now you can include that template in other templates that need the JS code.
Old post:
You can simply include the template file with that unbuffered JavaScript in any other Pug template file where you would like to use it. This can be done with the include keyword.
Edit:
It seems that this is only possible when you also include a mixin in the file holding the JavaScript. Work on a possibility to include pure JS code is on its way (according to these two GitHub issues on the Pug repo).
const declaration in it.gulp-pug, too, when I have no mixins in the file with the JS code (my fault, I had always tried it out in included files that already had mixins). Seems like the pug devs are working on a feature like this, according to the later comments on this issue report.If you use Template Inheritance and have a main template file (let's say body.pug) in which call say block content and a separate pug file for each page in which you extends ./body and define block content then the unbuffered code you put in body.pug will be available in every child pug file.
For example if you put the following in body.pug:
- let goat = true
You will be able to use that in any child pug file:
nav
a( href='/') Home
a( href='/blog) Blog
if goat
a( href='/goat') Goat