将变量从Node.js Express传递到EJS HTML文件以切换警报显示的方法是什么?

huangapple go评论69阅读模式
英文:

How can I pass a variable from Node.js Express to an EJS HTML file for toggling alert displays?

问题

以下是要翻译的内容:

嗨,基本上我正在尝试从我的app.js文件发送一个变量到我的ejs HTML文件,以便我可以切换警报显示的时机。

这是我app.js 中这部分代码的样子:
在此输入图片描述

这是我的第一次尝试:
在此输入图片描述
我尝试在定义ejs文件中的变量searcherror时加入各种括号,如<%= %>,<= =>,{{ }},等等(都带引号和不带引号),但都不起作用。

经过相当多的研究,我得出结论,由于某种原因,我无法在HTML的script标签中访问我的ejs变量。

为了应对这个问题,我创建了这个解决方法,我相信它应该可以工作,但出于某种原因它没有。注意:如果我关闭隐藏,div确实会显示出正确的文本值。
在此输入图片描述

app.js文件顶部的内容:
在此输入图片描述

非常感谢您的任何建议!

英文:

Hey so basically I am trying to send a variable from my app.js file to my ejs html file so that I can toggle when an alert is displayed.

This is what my app.js for this part of code looks like:
enter image description here

This is what my first attempt was:
enter image description here
I tried putting all sorts of brackets like <%= %>, <= =>, {{ }}, ect.(all with and w/o quotation marks) around searcherror when I am defining the variable in the ejs file but none of them worked.

After doing a fair amount of research, I came to the conclusion that I am unable to access my ejs variables inside of script tags in html for whatever reasons.

To combat this, I created this work around which I believe should work, but for whatever reason it does not. Note: the div does show up with the correct text value if I turn off hidden.
enter image description here

Stuff at top of app.js file:
enter image description here

Any input would be much appreciated!

答案1

得分: 1

当您发布代码时,将实际文本发布出来而不是图像会更有帮助,这样其他人就可以复制和粘贴。

作为示例,这对我有效:

Express路由:

router.get("/supersecretroute", (req, res, next) => {
  const someVar = { person: { name: "Tristan", display: false } };
  res.render("pages/index", { someVar });
});

index.ejs:

<main>
    <section id="some-section">
        <h2>Variable</h2>
        <p display="<%= someVar.person.display %>">
            <%= someVar.person.name %>
        </p>
    </section>
</main>
英文:

When you post code, it's helpful to post the actual text rather than images, so folks can copy and paste.

As an example, this worked for me:

Express route:

router.get(&quot;/supersecretroute&quot;, (req, res, next) =&gt; {
  const someVar = { person: { name: &quot;Tristan&quot;, display: false } };
  res.render(&quot;pages/index&quot;, { someVar });
});

index.ejs:

    &lt;main&gt;
        &lt;section id=&quot;some-section&quot;&gt;
            &lt;h2&gt;Variable&lt;/h2&gt;
            &lt;p display=&quot;&lt;%= someVar.person.display %&gt;&quot;&gt;
                &lt;%= someVar.person.name %&gt;
            &lt;/p&gt;
        &lt;/section&gt;
    &lt;/main&gt;

huangapple
  • 本文由 发表于 2023年6月1日 05:05:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定