在EJS中渲染变量为HTML [英] Render a variable as HTML in EJS

查看:996
本文介绍了在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?或者我必须使用像玉的东西?

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可以使用

<% 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文档

For more, see the full ejs documentation

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

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