在Jade模板中包含SVG xml [英] Include SVG xml in Jade template

查看:96
本文介绍了在Jade模板中包含SVG xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个Jade mixin,它可以从文件系统中读取文件,并将其回显到呈现的HTML中?

Is it possible to create a Jade mixin, which reads a file from the file system, and echoes it into the rendered HTML?

我尝试过了...

mixin svg(file)
    - var fs = require("fs");
    - var xml = fs.readFileSync(file)
    div= xml

...但失败,因为require不存在.

... but it fails because require does not exist.

推荐答案

我想有两种方法可以实现此目的.后一种方法只是在不使用mixins的情况下为您所接受的简单方法.第一个解决方案总结了您的方法:

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:

确保在玉器模板解析期间所需的功能可用(范围内).假设您使用的是快递,则可能看起来像这样:

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')
  })
});

现在,您的mixin应该可以进行两个较小的修改:

Now your mixin should work with two minor modifications:

mixin svg(file)
  - var xml = fs.readFileSync(file)
  div!= xml

您甚至可以将{ require: 'require' }作为本地内容传递给Jade模板,并使用原始的mixin代码.请注意,在任何情况下,都必须禁止使用!=对输出进行转义,以便传输SVG标记,以便对其进行解释和呈现,而不是将其显示为(HTML)文本.另外请注意,fs驻留在您的应用/控制器代码中,并且必须相对于它来表示路径,例如:

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:或者只使用include(不使用mixins)

Jade能够包含其他类型的内容,因此很简单

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

也做这项工作.不幸的是,这不能动态工作,因此您不能在mixins中使用传递的变量包含文件.但是:只要您不打算使用其他逻辑来丰富您的mixin,该解决方案甚至不会产生(生成)更多的代码.

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.

这篇关于在Jade模板中包含SVG xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆