Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include SVG xml in Jade template

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.

like image 562
Billy Moon Avatar asked May 28 '14 09:05

Billy Moon


1 Answers

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:

A: Pass variable require or fs to your jade template

Make 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')

B: Or just use include (without mixins)

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.

like image 112
matthias Avatar answered Sep 22 '22 17:09

matthias