I have created a <symbol>
to be reused many times in a document, and it works very well:
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,125,0);stop-opacity:1" />
</linearGradient>
<polygon id="hexagon" points="10,0 1.5,5 1.5,15 10,20 18.5,15 18.5,5" />
<polygon id="checkmark" points="3.5,21 5,19 7.5,22 15,14 16,15.5 7.5,24.5"/>
<symbol id="awsHex" viewBox="2 -2 300 300">
<use href="#hexagon" transform="translate(0 0) scale(4)"
fill="url(#grad1)"
stroke="#FFD600"
stroke-width="0.5" />
<use href="#hexagon" transform="translate(30 14)"
fill="#00AA00" opacity="100%" />
<use href="#checkmark" transform="translate(30,5.5)" fill="#FFF" />
</symbol>
</defs>
It works well and I can use it multiple times like this:
<use href="#awsHex" transform="translate(0 0)" />
<use href="#awsHex" transform="translate(120 0)"/>
<use href="#awsHex" transform="translate(60 105)"/>
<use href="#awsHex" transform="translate(180 105)"/>
I would like to put a text element in the <symbol>
so I can keep multiplying reuse while keeping the text inside the symbol.
<ref id="paramText" param="text-label">hexLabel</ref>
<symbol id="awsHex" viewBox="2 -2 300 300">
<use href="#hexagon" transform="translate(0 0) scale(4)"
fill="url(#grad1)"
stroke="#FFD600"
stroke-width="0.5" />
<use href="#hexagon" transform="translate(30 14)"
fill="#00AA00" opacity="100%" />
<use href="#checkmark" transform="translate(30,5.5)" fill="#FFF" />
<text id="myLabel" x="40" y="50" font-family="Helvetica"
font-weight="bold" text-anchor="middle" fill="white" font-size="10">
<tref xlink:href="#paramText" />
<param name="text-label" value="text-label" />
</text>
</symbol>
That obviously doesn't work, which is why I'm here.
Is there no way to reuse a symbol with a text element by passing in and overriding the text content? It seems I can override any attributes, but not the content of the element?
Is there a workaround to overcome this difficulty of svg
? It looks like they were working on this in the SVG standard but maybe it is not implemented yet? SVG Parameters docs
CodePudding user response:
No.
Even if you could, symbols are not intended to be parameterised. Symbols are for when you want to reuse the identical graphic multiple times.
You could use a symbol to represent the background of your text graphic, then just add a new <text>
element each time for the text part.
Or you could use javascript to implement a custom element.
<thing text="whatever"/>
Your JS would look for every <thing>
elements and replace it with a <symbol>
element and a <text>
element.