如何在jade中引入CSS文件(不使用链接)

10

我有这个jade文件:

!!! 5
html
  head
    title test include
    style(type='text/css')
      //- DOES NOT WORK!
      include test.css
  body
    //- works
    include test.css
    div 
      //- works
      include test.css

输出结果:

$ jade -P test.jade 
rendered test.html
$ cat test.html
<!DOCTYPE html>
<html>
  <head>
    <title>test include</title>
    <style type="text/css">
      //- DOES NOT WORK!
      include test.css
    </style>
  </head>
  <body>body { color: peachpuff; }

    <div> body { color: peachpuff; }

    </div>
  </body>
</html>

当然,我可以简单地链接CSS文件,但我不想这样做。


我不认为这是可能的,但为什么不选择简单的解决方案呢? - jsbeckr
2
我猜你想在服务器文件中将CSS与HTML分离,但在HTML中提供样式以避免获取CSS的额外请求。这是错误的:你会增加额外的计算(文件包含),而这个文件不会每次都被请求,因为它会被缓存。 - Arnaud Rinquin
7个回答

13

我还没有测试过它(目前不在我的开发电脑上),但是这样做有可能会起作用:

!!!
head
  title test include
  | <style type='text/css'>
  include test.css
  | </style>

顺便问一下,我找到了HTML2Jade的在线转换器,但没有找到Jade2HTML的。有什么好的建议吗?


谢谢,可以工作!我不知道任何在线转换器。但我找到了第一个失败的原因:“只接受文本的标签(如脚本和样式)不需要前导|字符”(https://github.com/visionmedia/jade) - user470370

9

来自Jade文档:

doctype html
html
  head
    style
      include style.css
  body
    h1 My Site
    p Welcome to my super lame site.

它完美地工作。


虽然这个代码可以工作,但我想指出它与原问题中的代码是相同的,唯一的区别是版本(已经过去了3年)。 - Zhiyong

2

fs 作为数据传递,您就可以

style !{fs.readFileSync("index.css").toString()}

虽然不完全跨实现安全,但仍是一个不错的技巧。 - coolaj86

2

Arnaud的答案对我有用,但后来我发现这个方法更简洁:

doctype
head
  title test include
  style(type="text/css"): include test.css

(type="text/css")是可选的,具体情况视需求而定。


0
style(type="text/css").
  #{css}

尝试使用 pug.render(..., { css: yourCssString })


0
在当前版本的Jade(0.35.0)中,只需编写include style.css即可。完整示例(假设您正在编写位于views文件夹中的index.jade文件,而您的样式位于assets文件夹中):
!!!
html
   head
       include ../assets/bootstrap3/css/bootstrap-theme.css
       include ../assets/bootstrap3/css/bootstrap.css
body
   h1 Hi!

请注意模板中缺少style标签,这将由Jade自动插入(多好的功能!)。

从1.0.0版本开始(至少是这样),似乎不再是这种情况:如果您没有指定更多的细节,CSS将仅以逐字方式包含,而不是在样式标签中。 - Tim Perry
你必须包括一个样式标签,它不会自动添加。 - Nicekiwi

-1
一个可能的解决方案是:
style(type="text/css")
    #{css}

然后在res.render(...)调用中传递css文本。

这只是他问题的一个解决方案,我并没有真正理解。;) - jsbeckr
1
请看我的有关他目标的评论 ;) - Arnaud Rinquin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接