mde / ejs

Embedded JavaScript templates -- http://ejs.co

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to ignore template syntax in whole .ejs file on server side

zcs02468 opened this issue · comments

commented

I think it's a pain to use a single .ejs template on both the server and client side.
Can nunjucks provide something like
{ raw }{ endraw }
This method is to ignore all the content in the middle and ensure that the original output includes <%= %> <%- %> ... instead of using <%% %>,
which is easy to use ,
but it is not very convenient when there are too many template lines

I'm not quite sure what you're asking here, but if you're wanting output with percent signs not to be rendered, you can initially use a different delimiter character (e.g., @) in your template string, and then either render it using the delimiter option, or run it through a string-replacement function to convert those characters back to percents before rendering.

Please feel free to reopen if this doesn't answer your question.

commented

I hope to have the following syntax structure, because I have a lot of ejs templates that need to be executed on the client side and the server side at the same time, and their codes are exactly the same

input

<div>
  <% for( let index = 0; index < list; index++ ) { %>
  <div><%= list[index] %></div>
  <% } %>
</div>

<% raw %>
<script>
  <div>
    <% for( let index = 0; index < list; index++ ) { %>
    <div><%= list[index] %></div>
    <% } %>
  </div>
</script>
<% endraw %>

Output

<div>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

<script>
  <div>
    <% for( let index = 0; index < list; index++ ) { %>
    <div><%= list[index] %></div>
    <% } %>
  </div>
</script>

Sounds like what you're trying to do is conditionally include some EJS code in the middle of the template, only on the client. You could just not render the client-only sections for your server version, based on some constant value (set by env, but passed, or similar). Or you could use include with conditional paths, that return two different things.

commented

Do you mean to rewrite the include method, and do the conditional judgment import in this method?

I mean use a conditional variable for the filepath the include. One of those paths could point to a basically empty template. Even if you pass variables to it, it can just return an empty string.