【问题标题】:How to include a css file in jade (without linking it)如何在翡翠中包含一个css文件(不链接它)
【发布时间】:2012-05-15 06:54:26
【问题描述】:

我有这个玉文件:

!!! 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 文件,但我不想这样做。

【问题讨论】:

  • 我不认为这是可能的,但为什么不是简单的解决方案?
  • 我猜您想在服务器文件中将 CSS 与 HTML 分开,但在 html 中提供样式以避免额外请求获取 CSS。这是错误的:您为一个不会每次都请求的文件添加额外的计算(文件包含),因为它会被缓存。

标签: node.js pug


【解决方案1】:

我还没有测试它(不是在我的开发计算机 ATM 上)但是有机会做这样的事情可以工作:

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

顺便说一句,我找到了 HTML2Jade 在线转换器,但没有找到 Jade2HTML。知道在哪里可以找到它吗?

【讨论】:

  • 谢谢你,工作!我不知道任何在线转换器。但我首先找到了失败的原因:“只接受脚本和样式等文本的标签不需要前导|字符”(github.com/visionmedia/jade
【解决方案2】:

来自jade docs

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

效果很好。

【讨论】:

  • 虽然这确实有效,但我想补充一点,它与原始问题中的代码相同,不同之处在于版本(已过去 3 年)。
【解决方案3】:

fs作为数据传入即可

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

【讨论】:

  • 不完全是跨实现安全的,但仍然是一个很好的 hack
【解决方案4】:

Arnaud 的回答对我有用,但后来我发现这更简洁:

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

(type="text/css") 也是可选的,具体取决于您的情况。

【讨论】:

    【解决方案5】:

    在当前的 Jade (0.35.0) 版本中只写就足够了 include style.css

    完整示例(假设您正在编写 index.jade,它位于 views 文件夹中,而您的样式位于 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 只是逐字包含,而不是在样式标记中跨度>
    • 必须包含样式标签,不会自动添加。
    【解决方案6】:
    style(type="text/css").
      #{css}
    

    pug.render(..., { css: yourCssString })试试这个

    【讨论】:

      【解决方案7】:

      一个可能的解决方案是:

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

      然后在res.render(...)调用中传递css-text。

      【讨论】:

      • 这是..这只是他的问题的解决方案,我根本不明白。 ;)
      • 查看我对他的目标的评论;)
      猜你喜欢
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多