Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use template literals (``) within template literals?

I have a very specific edge case which I need to use a template literal within a template literal but can't get it done.

The code looks something like this:

<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>

However I will have to wrap that in a function, while maintaining the value of the SOMELINK variable, this causes errors to happen. Whether I escape the ticks or not.

someFunction (`<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>`)

With escaped ticks I get the following error message:

Error: Expected SOMELINK but none provided

Without, I get:

Unexpected token, expected ","

How do I handle this?

Edit: It should probably be noted that the code being passed in someFunction will be rendered and it need to be used. It will eventually be passed in to another tag through dangerouslySetInnetHTML. So it will look something like this:

<div dangerouslySetInnerHTML={{__html: someFunction(`<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>`)}}/>

Not sure if this is relevant, but someFunction just does some modifications on the text.

like image 433
theJuls Avatar asked May 25 '18 16:05

theJuls


3 Answers

I think you're overcomplicating it. If you only need to maintain the value of SOMELINK, this should work:

someFunction(`<p>Something something <a href="${SOMELINK}/blah">SomeLink</a></p>`)
like image 152
imjared Avatar answered Sep 22 '22 17:09

imjared


You can do like:

someFunction(`<p>Something something <a href={${SOMELINK}/blah>SomeLink</a></p>`);
like image 24
Hitesh Chaudhari Avatar answered Sep 24 '22 17:09

Hitesh Chaudhari


Try this

someFunction("<p>Something something <a href={"+`${SOMELINK}/blah`+"}>SomeLink</a></p>")

I think you also need to make the route relative

"<p>Something something <a href={/"+`${SOMELINK}/blah`+"}>SomeLink</a></p>"
like image 35
supra28 Avatar answered Sep 26 '22 17:09

supra28