简体   繁体   English

我该如何为树枝变量var中未定义的内容编写if / else语句?

[英]How would I write an if/else statement for something that is undefined with a twig var?

I'm using twig to declare a var user: 我正在用树枝声明一个var用户:

<script type="text/javascript">
   {% if user is defined %}
   var user = {
    example: {{ userjson | raw }}
   };
   {% endif %}
 </script>

This checks to see if a user is logged in, if not my console returns this: 这将检查用户是否已登录,如果不是,则控制台返回以下信息:

Uncaught ReferenceError: user is not defined

I want to be able to display a message if the user is not defined but I can't think of a way to do that. 如果用户未定义,我希望能够显示一条消息,但我想不出一种方法。 Right now I have this: 现在我有这个:

if(user){
    console.log('hello');
} else {
    console.log('undefined');
}



// This checks is the user information
var userId = user.example.id;


console.log(user.example.money);

Ok so I figured this out: 好的,所以我弄清楚了:

<script type="text/javascript">
   {% if user is defined %}
   var user = {
    example: {{ userjson | raw }}
   };
   {% else %}
   var user = false;
   {% endif %}
 </script>

Then I just check to see if the var user is false, and if it's not then I do something else. 然后,我只是检查var用户是否为假,如果不是,则执行其他操作。

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

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