Reputation: 738
I know little about SVG but I'm trying to make the text parameter variable, so I could iterate and create SVG Markup's which vary solely by (variable) text. This is what I can do (borrowed from the site whose API I'm using)
'<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">' +
'<rect stroke="black" fill="${FILL}" x="1" y="1" width="22" height="22" />' +
'<text x="12" y="18" font-size="12pt" font-family="Arial" font-weight="bold" ' +
'text-anchor="middle" fill="${STROKE}" >hello world
</text></svg>'
But this is what I would like (or something that works like it):
'<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">' +
'<rect stroke="black" fill="${FILL}" x="1" y="1" width="22" height="22" />' +
'<text x="12" y="18" font-size="12pt" font-family="Arial" font-weight="bold" ' +
'text-anchor="middle" fill="${STROKE}" >"${TEXT}"</text></svg>'
so I can dynamically change the text.
Upvotes: 0
Views: 4810
Reputation: 102194
You actually can use ${TEXT}
, and it does work (except for IE).
The name of this is template literal:
Template literals are string literals allowing embedded expressions.
However, for this to work, you should have enclosed the whole string with back-ticks (`).
Here is a working demo using your string (with little changes):
var FILL = "tan", STROKE = "black", TEXT = "Hello World";
var svgMarkup = `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="24"
xmlns="http://www.w3.org/2000/svg"><rect stroke="black" fill="${FILL}" x="1" y="1"
width="22" height="22" /><text x="12" y="18" font-size="12pt" font-family="Arial"
font-weight="bold" text-anchor="start" fill=${STROKE}>${TEXT}</text></svg>`;
var div = document.getElementById("foo");
div.innerHTML = svgMarkup;
<div id="foo"></div>
Upvotes: 0
Reputation: 738
Ok I figured it out; in retrospect, it was kind of a stupid question 😂. Just replace the faulty ${TEXT} tag with + varName +
like in normal string concatenation:
var svgMarkup = '<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">' +
'<rect stroke="black" fill="${FILL}" x="1" y="1" width="22" height="22" />' +
'<text x="12" y="18" font-size="12pt" font-family="Arial" font-weight="bold" ' +
'text-anchor="middle" fill="${STROKE}" >'+ varName +'</text></svg>';
Upvotes: 1