Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return html in d3 text function?

I want to be able to return html from the text function like this:

textEnter.append("tspan")
          .attr("x", 0)
          .text(function(d,i) {
             return 'some text' + '<br/>' + d.someProp;
           })

Tried to use &lt;br&gt;, but didnot work. How do I achieve this?

like image 263
Isaac Avatar asked May 20 '13 19:05

Isaac


1 Answers

EDITED ANSWER

Just noticed that you're working with a tspan here. Unfortunately you can't insert line breaks into svg text elements. Multiline text with SVG requires breaking up the text yourself and then laying it out by setting the dy attribute. D3 makes the laying out process pretty straight forward, but it still takes extra work.

More info in the intro paragraph here: http://www.w3.org/TR/SVG/text.html

OLD ANSWER (applies if using html elements, not svg)

D3 has a separate method for this: the html() method, which works just like text() but unescaped. More info here. So, easily enough, you just need:

textEnter.append("tspan")
      .attr("x", 0)
      .html(function(d,i) {
         return 'some text' + '<br/>' + d.someProp;
       })
like image 184
meetamit Avatar answered Oct 30 '22 07:10

meetamit