简体   繁体   中英

How to use EJS tags in a JS string

<%
   let myString = "this is a string %> with special characters";
   let myOtherString = "this is a string <% with special characters";
   // Do something
%>

I need to use these special characters in my JS string <% and/or %>. But EJS template would return errors: Could not find matching close tag for "<%" or SyntaxError: Invalid or unexpected token while compiling ejs for %>

How should I go about this?

You could simply concatenate two strings together:

let myString = "this is a string %" + "> with special characters";

or with template literals to make it a bit less ugly:

let startTag = '<' + '%';

let myString = `this is a string ${startTag} with special characters`;

For the record, their documentation lists options to change the starting/ending tags, which they call delimiters, in case you prefer eg <! and !> . Their documentation also mentions that <%% should print <% but I personally don't know if this works within a <% code %> block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM