在 EJS 中将变量呈现为 HTML [英] Render a variable as HTML in EJS

查看:40
本文介绍了在 EJS 中将变量呈现为 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Node.js 的表单库(表单),它将在后端为我呈现一个表单作为所以:

I am using the Forms library for Node.js (Forms), which will render a form for me on the backend as so:

var signup_form = forms.create({
    username: fields.string({required: true})
    , password: fields.password({required: true})
    , confirm:  fields.password({
        required: true
        , validators: [validators.matchField('password')]
    })
    , email: fields.email()
});
var signup_form_as_html = signup_form.toHTML();

最后一行 var signup_var signup_form_as_html = signup_form.toHTML(); 创建一个如下所示的 HTML 块:

The final line var signup_var signup_form_as_html = signup_form.toHTML(); creates a block of HTML which looks as such:

<div class="field required"><label for="id_username">Username</label><input type="text" name="username" id="id_username" /></div><div class="field required"><label for="id_password">Password</label><input type="password" name="password" id="id_password" /></div><div class="field required"><label for="id_confirm">Confirm</label><input type="password" name="confirm" id="id_confirm" /></div><div class="field"><label for="id_email">Email</label><input type="text" name="email" id="id_email" /></div>

基本上只是一长串 HTML.然后我尝试使用以下代码使用 EJS 和 Express 渲染它:

Basically just a long string of HTML. I then try to render it using EJS and Express using the following code:

res.render('signup.ejs', {
    session: loginStatus(req)
    , form: signup_form_as_html
});

但是在渲染 HTML 时,它只是我上面发布的字符串,而不是实际的 HTML(因此是我想要的表单).有没有办法使用 EJS 使该字符串呈现为实际的 HTML?还是我必须使用 Jade 之类的东西?

But on rendering the HTML is simply the string that I posted above, rather than actual HTML (and thus a form as I want). Is there any way to make that string render as actual HTML using EJS? Or will I have to use something like Jade?

推荐答案

使用 EJS,您可以拥有多个标签:

With EJS you can have several tags:

    <% code %>

...这是被评估但没有打印出来的代码.

... which is code that is evaluated but not printed out.

    <%= code %>

... 这是被评估并打印出(转义)的代码.

... which is code that is evaluated and printed out (escaped).

    <%- code %>

... 这是被评估和打印出来的代码(没有转义).

... which is code that is evaluated and printed out (not escaped).

因为你想打印你的变量而不是转义它,你的代码将是最后一种类型(带有 <%-).在你的情况下:

Since you want to print your variable and NOT escape it, your code would be the last type (with the <%-). In your case:

    <%- my_form_content %>

有关更多标签,请参阅完整的 EJS 文档

这篇关于在 EJS 中将变量呈现为 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆