Node.js 脚本中的条件句。玉佩

Node.js 脚本中的条件句。玉佩,node.js,pug,Node.js,Pug,在Jade中,是否可以在dynamicscript部分中创建条件if语句 例如: doctype html html head script. -if( locals.display_JS ) console.log("Display_JS is TRUE") -else console.log("Display_JS is FALSE") script | function bar(){ if(true) | console.lo

在Jade中,是否可以在dynamicscript部分中创建条件if语句

例如:

doctype html
html
 head
  script.
   -if( locals.display_JS )
    console.log("Display_JS is TRUE")
   -else
    console.log("Display_JS is FALSE")
script
    | function bar(){
    if(true)
      | console.log("Ran this")
    else
      | console.log("Don't run this")
    | }
(locals.display_JS是res.render中传递给Jade的参数。)

如果display_JS为true,则所需的输出应如下所示:

<script ...>console.log("Display_JS is TRUE")</script>
console.log(“Display_JS为TRUE”)
然而,结果是:

<script>
 -if( locals.display_JS )
  console.log("Display_JS is TRUE")
 -else
  console.log("Display_JS is FALSE")
</script>

-if(locals.display_JS)
log(“Display_JS为TRUE”)
-否则
log(“Display_JS为FALSE”)

可能是我想错了。我的目标是根据发送到res.render的参数呈现不同的javascript函数

Jade不会弄乱脚本块中的任何内容。如果您真的需要在脚本块中使用jade逻辑,您可以使用一些技巧并执行以下操作:

script.
    if(!{run_this}){
        console.log("Ran This!");
    }
路由器代码:

router.get('/', function(req, res){
    res.render('index', {run_this:true});
}); 
玉码:

div
| <script type='text/javascript'>
if(run_this)
    | console.log("Ran this!");
else
    | console.log("Didn't run this");
| </script>

可以用另一种方法,使用。每当您想要嵌套javascript代码时

doctype html
html
 head
  script
    if( locals.display_JS )
      .
         /** Some JS code **/
         console.log("Display_JS is TRUE")
    else
      .
         console.log("Display_JS is FALSE")

当您使用
脚本时。
之后的所有内容都将被jade解释为纯文本。如果需要混合使用标记和纯文本,可以使用
。例如:

doctype html
html
 head
  script.
   -if( locals.display_JS )
    console.log("Display_JS is TRUE")
   -else
    console.log("Display_JS is FALSE")
script
    | function bar(){
    if(true)
      | console.log("Ran this")
    else
      | console.log("Don't run this")
    | }

谢谢但是我注意到了!{}实际上在脚本块中工作。例如:我可以用这个插入变量run_!{运行这个}。如果我能在最短的时间内运行该条件!{},那么它就可以工作了。然而!{if(run_this){console.log(“run this”);}}将生成一个错误。这是您可以采取的另一种方法。这是一种不同于在脚本标记中运行jade条件的方法。我已经更新了我的答案,加入了这种方法的工作原理。太棒了!也许还有另一个问题,但这个问题是如何解决的!{}还是工作?例如{Math.Floor(25.5)}有效,但是!{if(Math.floor(25.5)==25){return 25}}不起作用。似乎您可以使用tin完成一组有限的javascript函数!{}. 但是if/for/while等条件会产生错误。{}不允许在脚本标记中运行jade条件。这些括号是jade用来逃跑的。基本上,它将括号内的任何变量的值插入html文档中。在我们的例子中,它将true/false直接插入javascript if语句内的脚本块中。这个确保它不会对插入的任何字符进行编码。请看此处有关转义的部分: