45

I'm using express.js with EJS templates and i'm trying to do something like this:

<%= "<a href='#'>Test</a>" %>

but it prints this:

&lt;a href='#'&gt;Test&lt;/a&gt;

how can i print "html safe" strings?

3 Answers 3

76

You should use html code everywhere, and use the EJS tags only where you need dynamic data. Example:

<a href='<%= user.id %>'><%= user.name %</a>

To specifically answer your question you can use <%- "<tags_here>" %> to output unescaped HTML data.

Sign up to request clarification or add additional context in comments.

7 Comments

the problem is that when i do this: <%= partial('my_link') %> it prints that way too
Ah if you want html to not be escaped you should do this <%- partial('my_link') %>
No problem, for more info on EJS check the github repo: github.com/visionmedia/ejs
You could still have answered to the question. What if others come look this question expecting to find out how to print unescaped stuff?
is there something similar to echo from php that lets you print data from within a <% %> statement?
|
35

for raw output html in ejs you can use this code

<%- "<a href='#'>Test</a>" %>

Comments

17

This are the available options according to the docs

  1. <% 'Scriptlet' tag, for control-flow, no output
  2. <%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
  3. <%= Outputs the value into the template (HTML escaped)
  4. <%- Outputs the unescaped value into the template
  5. <%# Comment tag, no execution, no output
  6. <%% Outputs a literal '<%'
  7. %> Plain ending tag
  8. -%> Trim-mode ('newline slurp') tag, trims following newline
  9. _%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it

Looks like the option you need is the number 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.