繁体   English   中英

如何使用 Jade / Pug 渲染内联 JavaScript?

[英]How can I render inline JavaScript with Jade / Pug?

我正在尝试让 JavaScript 使用 Jade(http://jade-lang.com/)在我的页面上呈现

我的项目在带有 Express 的 NodeJS 中,一切工作正常,直到我想在头部编写一些内联 JavaScript。 即使从 Jade 文档中获取示例,我也无法让它工作我错过了什么?

玉模板

!!! 5
html(lang="en")
  head
    title "Test"
    script(type='text/javascript')
      if (10 == 10) {
        alert("working")
      }
  body

结果在浏览器中呈现 HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <title>"Test"</title>
  <script type="text/javascript">
    <if>(10 == 10) {<alert working></alert></if>}
  </script>
</head>
<body>
</body>
</html>

绝对是这里的一些东西有什么想法吗?

只需使用后面带有点的“脚本”标签。

script.
  var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}

https://github.com/pugjs/pug/blob/master/examples/dynamicscript.pug

:javascript过滤器在7.0 版中被移除

文档说您现在应该使用script标签,然后是. char 并且没有前面的空格。

例子:

script.
  if (usingJade)
    console.log('you are awesome')
  else
    console.log('use jade')

将被编译为

<script>
  if (usingJade)
    console.log('you are awesome')
  else
    console.log('use jade')
</script>

使用指定类型的脚本标签,只需在点之前包含它:

script(type="text/javascript").
  if (10 == 10) {
    alert("working");
  }

这将编译为:

<script type="text/javascript">
  if (10 == 10) {
    alert("working");
  }
</script>

仅不使用脚本标签。

解决方案|

script
  | if (10 == 10) {
  |   alert("working")
  | }

或带有.

script.
  if (10 == 10) {
    alert("working")
  }

我的答案的第三个版本:

这是内联 Jade Javascript 的多行示例。 我认为不使用-就无法编写它。 这是我在部分中使用的 flash 消息示例。 希望这可以帮助!

-if(typeof(info) !== 'undefined')
  -if (info)
    - if(info.length){
      ul
        -info.forEach(function(info){
          li= info
      -})
  -}

您尝试获取的代码是编译问题中的代码吗?

如果是这样,你不需要两件事:第一,你不需要声明它是 Javascript/a 脚本,你可以在输入-后开始编码; 其次,在你输入-if你也不需要输入{}之后。 这就是让 Jade 非常甜美的原因。

--------------下面的原始答案---------------

尝试if前面加上-

-if(10 == 10)
  //do whatever you want here as long as it's indented two spaces from
   the `-` above

也有大量翡翠的例子在:

https://github.com/visionmedia/jade/blob/master/examples/

对于多行内容,jade 通常使用“|”,但是:

仅接受文本(如 script、style 和 textarea)的标签不需要前导 | 特点

这就是说,我无法重现您遇到的问题。 当我将该代码粘贴到玉模板中时,它会生成正确的 output 并在页面加载时提示我警报。

我会检查你的空白。

你也可以把你的 JS 文件作为一个包含进来。 我知道这不是问题的答案,但您会发现调试 JS 更容易,因为任何错误最终都会引用真实文件中的行号。

使用:javascript过滤器。 这将生成一个脚本标记并将脚本内容转义为 CDATA:

!!! 5
html(lang="en")
  head
    title "Test"
    :javascript
      if (10 == 10) {
        alert("working")
      }
  body
script(nonce="some-nonce").
  console.log("test");

//- Workaround
<script nonce="some-nonce">console.log("test");</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM