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();
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>
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 });
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?
It is possible to access JS variable in . ejs file. You just need to pass the JS object as second parameter of res. render() method.
A variable declaration starts with the keyword var followed by the variable name, e.g. : var myVariable; The variable declaration ends with a semi-colon. The names of the variables in EJS-templates are case-sensitive: myVariable and myvariable are different variables.
I figured out how to render strings: var http = require('http'); var ejs = require('ejs'); var server = http. createServer(function(req, res){ res. end(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 %>
For more tags, see the full EJS documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With