Include SVG xml in Jade template

后端 未结 3 2032
感情败类
感情败类 2021-02-04 10:06

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)
            


        
3条回答
  •  不思量自难忘°
    2021-02-04 10:47

    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.

提交回复
热议问题