简体   繁体   中英

IF conditional in EJS with Script tag doesn't work

I've some problem in here. I put script tag inside IF Conditional. Nah, script tag is running when condition is TRUE or FALSE.

For example

<% if (info) { %>
    <p><%=info%></p>
            <script type="text/javascript">
            alert("Hi")
            </script>
    <% } %>

Result :

IF = TRUE

alert("Hello world")
<p>Hello world</p>

IF = FALSE

alert("Hello world")

Paragraph attributes is rendering when IF conditional is TRUE. But script tag is running when IF Conditional is TRUE or FALSE, what i want the script tag running like HTML attributes.

Why this is happened? Thanks

Okay, i answer my own questions. This is solved by added <% if (info.length > 0) { %>

Since my route file like this

function isAuth(req, res, next){
    var token = req.session.token;
    if(token){
        jwt.verify(token, 'jwtsecret', function(err, decoded){
            if(err){
                req.flash('info', err)
                res.info = req.flash()
                res.redirect('/login')
                return;
            }
            req.decoded = decoded;
            req.session.username = decoded.username
            next();
        })
    }
    else{
        req.flash('info', "Please login first")
        res.redirect('/login')
    }
};

Router.get('/login', function(req, res){
    console.log(req.flash)
    res.render('../views/login', {info : req.flash('info')})
})
<% if (info.length > 0) { %>
  <script type="text/javascript">
    alert("Hello world")
  </script>
  <% } %>

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