简体   繁体   中英

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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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