簡體   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