How do I display html encoded values in svg?

2020-02-14 06:46发布

问题:

I am using d3 to generate svg and end up with markup similar to the following:

<text class="rule" text-anchor="middle">&amp;pound;10K</text>

Compare to similar html that renders as expected.

<div>
    &pound;20,160 - &pound;48,069
</div>

Is there a property I need to set on the svg tag to get a similar type of encoding? I tried adding a meta tag to the page <meta name="content" content="application/xhtml+xml; charset=utf-8" /> but this did not work.

回答1:

HTML entities are not defined in SVG. You can either use the actual unicode character or use the foreignObject element to embed HTML into your SVG.



回答2:

Since you are using d3js, you can use the unicode as well.

Example to append text to span:

svg.append('span')
   .text('Pound: ' + '\u00A3' + ' or ' + '\uFFE1');