Display variable as HTML in EJS

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

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(); 

The final line is var signup_var signup_form_as_html = signup_form.toHTML(); creates an HTML block that looks like this:

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

Basically just a long line of HTML. Then I try to do this using EJS and Express using the following code:

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

But when rendering HTML, it's just the line I posted above, not the actual HTML (and therefore the form I want). Is there a way to make this string render as actual HTML using EJS? Or will I have to use something like Jade?

+61
express ejs
Apr 26 2018-12-12T00:
source share
2 answers

With ejs you can have

 <% code %> 

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

 <%= code %> 

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

 <%- code %> 

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

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

 <%- my_form_content %> 

For more details see the full ejs documentation

+192
Apr 26 2018-12-12T00:
source share

October 2017 Update

A new ejs (v2, v2.5.7) is developing here: https://github.com/mde/ejs An old ejs (v0.5.x, 0.8.5, v1.0.0) is available here https://github.com/ tj / ejs

Now with ejs you can do even more. You can use:

  • Shielded output with <%= %> (control function configuration)
  • Raw source output with <%- %>
  • Newline slurping mode with tag -%>
  • Slurp all whitespace for control flow using <%_ _%>
  • Control stream with <% %>

So in your case it will be <%- variable %> where variable is something like

 var variable = "text here <br> and some more text here"; 

Hope this helps someone. 🙂

0
Oct 08 '17 at 6:48
source share



All Articles