【问题标题】:IF conditional in EJS with Script tag doesn't work带有脚本标记的 EJS 中的 IF 条件不起作用
【发布时间】:2017-10-28 07:40:37
【问题描述】:

我这里有点问题。我把script标签放在IF Conditional里面。不,script 标签在条件为 TRUE 或 FALSE 时运行。

例如

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

结果:

如果=真

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

如果 = 假

alert("Hello world")

段落属性 在 IF 条件为 TRUE 时呈现。但是当 IF Conditional 为 TRUE 或 FALSE 时,script 标记正在运行,我希望 script 标记像 HTML 属性一样运行。

为什么会这样?谢谢

【问题讨论】:

  • 这可能与类型有关;在 JavaScript 中,!!'FALSE' === true
  • 那么我的代码有什么用?如果在 EJS 中有条件,是否不可能在内部使用脚本标签? @PaulS。

标签: javascript html node.js express ejs


【解决方案1】:

好的,我回答我自己的问题。通过添加&lt;% if (info.length &gt; 0) { %&gt;

解决了这个问题

因为我的路由文件是这样的

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>
  <% } %>

【讨论】:

  • 这是一个很好的分享例子。只要我们有解决方案,请不要犹豫,回答我们自己的问题。
猜你喜欢
  • 2016-03-06
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多