Is it possible to create a Jade mixin, which reads a file from the file system, and echoes it into the rendered HTML?
I tried this...
mixin svg(file)
- var fs = require("fs");
- var xml = fs.readFileSync(file)
div= xml
... but it fails because require
does not exist.
I guess there are two ways to achieve this. Latter one just shows the straight way in case not using mixins is acceptable for you. The first solution wraps up your approach:
require
or fs
to your jade templateMake sure that the needed functions are available (scoped) during jade template parsing. Assuming you're using express this might look like this:
app.get('/', function(req,res) {
res.render('portfolio.jade', {
title: 'svg with jade test',
fs: require('fs')
})
});
Now your mixin should work with two minor modifications:
mixin svg(file)
- var xml = fs.readFileSync(file)
div!= xml
You can even just pass { require: 'require' }
as a local to the jade template and use your original mixin code. Note that in any case you have to suppress escaping the output with !=
in order to transfer SVG markup so that it is interpreted and rendered instead of being displayed as (HTML) text. Also be aware that fs
lives in your app/controller code and paths must be expressed relative to it, e.g.:
mixin('public/images/my-logo.svg')
Jade is capable of including other type of contents, so a simple
div
include images/my-logo.svg
does this job as well. Unfortunately this doesn't work dynamically, so you cannot include files using passed variables within mixins. But: As long as you're not planning to enrich your mixin with additional logic, this solution doesn't even produce (way) more code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With