Lin Du
Lin Du

Reputation: 102457

ejs, how to add dynamic attributes of html tag?

I use express.js + ejs, I have two cases:

1.

<a href="<%= prevDisabledClass ? '' : ?page=<%=+page - 1%>%>">prev</a>

But it give me an error: Could not find matching close tag for "<%="./nundefined/nError: Could not find matching close tag for "<%=".

I want to get

prevDisabledClass ? <a href=''>prev</a> : <a href='?page=<%=+page - 1%>'>prev</a>

2.

like above, but dynamic add href attribute to html tag <a>

I want to get this:

prevDisabledClass ? <a>prev</a> : <a href='?page=<%=+page - 1%>'>prev</a>

How can I solve these two problem?

Upvotes: 4

Views: 3050

Answers (1)

skirtle
skirtle

Reputation: 29112

For the first one you currently have this:

<a href="<%= prevDisabledClass ? '' : ?page=<%=+page - 1%>%>">prev</a>

You can't nest <%=, try this instead:

<a href="<%= prevDisabledClass ? '' : ('?page=' + (page - 1)) %>">prev</a>

For the second one it'd be almost exactly the same but you'd move the condition around more of the output:

<a<%- prevDisabledClass ? '' : (' href="?page=' + (page - 1) + '"') %>>prev</a>

Here I've used <%- instead of <%= to ensure the " doesn't get HTML encoded.

It might be clearer to ditch the ?: altogether:

<% if (prevDisabledClass) { %>
    <a>prev</a>
<% } else { %>
    <a href="?page=<%= page - 1 %>">prev</a>
<% } %>

There's some duplication but it's much easier to read.

Upvotes: 3

Related Questions