How to use EJS inside HTML attributes?

Viewed 358

I have the following two cases where I want to use an EJS tag inside an HTML attribute.

CASE 1:

<input
   style="background-image: url(<%= img.URL %>)"
/>

CASE 2:

<input
    onchange="handleCheckboxChange(<%= img.URL %>)"
/>

I am unable to figure out why is it not working. The img object is passed correctly while rendering the template.

2 Answers

Case 2 translates to the following:

<input
    onchange="handleCheckboxChange(https://example.org)"
/>

Which is a syntax error

You need to wrap them inside quotes:

<input
    onchange="handleCheckboxChange('<%= img.URL %>')"
/>

I found a solution for the same, the ejs tags need to be wrapped inside quotes.

SOLUTION FOR CASE 1

<input
   style="background-image: url('<%= img.URL %>')"
/>

SOLUTION FOR CASE 2

<input
    onchange="handleCheckboxChange('<%= img.URL %>')"
/>
Related