在EJS中渲染变量为HTML

编程入门 行业动态 更新时间:2024-10-22 08:23:25
本文介绍了在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

本文发布于:2023-10-27 15:46:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:量为   EJS   HTML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!