Wiki source code of Display an Icon in a Script
Last modified by Eleni Cojocariu on 2026/08/25 16:24
Hide last authors
| author | version | line-number | content |
|---|---|---|---|
![]() |
1.1 | 1 | Render an icon of the wiki's [[Icon Theme>>doc:documentation.xs.admin.icons.icon-themes.WebHome]] from a Velocity script with the ##$services.icon## script service, which returns the markup and pulls in the stylesheets the theme needs. |
| 2 | |||
| 3 | 1. Print the icon by its name in [[the XWiki Icon Set>>doc:documentation.xs.admin.icons.icon-set.WebHome]], which returns XWiki syntax((( | ||
| 4 | {{code language="velocity"}} | ||
| 5 | The $services.icon.render('home') button returns to the wiki home page. | ||
| 6 | {{/code}} | ||
| 7 | ))) | ||
| 8 | 1. Call ##renderHTML## instead where the surrounding output is already HTML, which returns the markup itself((( | ||
| 9 | {{code language="velocity"}} | ||
| 10 | {{html}}<button class="btn btn-default">$services.icon.renderHTML('home') Home</button>{{/html}} | ||
| 11 | {{/code}} | ||
| 12 | ))) | ||
| 13 | 1. (Optional) Name a theme in the second argument to take the icon from that theme rather than the wiki's, and pass ##false## as a third argument to get an empty result instead of a fallback when the theme or the icon is missing((( | ||
| 14 | {{code language="velocity"}} | ||
| 15 | $services.icon.render('home', 'Silk') | ||
| 16 | $services.icon.render('home', 'Silk', false) | ||
| 17 | {{/code}} | ||
| 18 | ))) | ||
| 19 | 1. (Optional) Read the icon's metadata instead when your own code builds the markup, and pull the theme's resources yourself, which ##getMetaData## does not do((( | ||
| 20 | {{code language="velocity"}} | ||
| 21 | $services.icon.use($services.icon.currentIconSetName) | ||
| 22 | #set ($metadata = $services.icon.getMetaData('home')) | ||
| 23 | #if ($metadata.iconSetType == 'IMAGE') | ||
| 24 | {{html}}<img src="$metadata.url" alt=""/>{{/html}} | ||
| 25 | #elseif ($metadata.iconSetType == 'FONT') | ||
| 26 | {{html}}<span class="$metadata.cssClass" aria-hidden="true"></span>{{/html}} | ||
| 27 | #end | ||
| 28 | {{/code}} | ||
| 29 | ))) | ||
| 30 | 1. Save the page. The icons are drawn by the theme the wiki uses, as follows:((( | ||
| 31 | {{image reference="icon-script-result.png" size="medium" alt="A saved page rendering a house icon in a sentence and in a button labelled Home, both highlighted"/}} | ||
| 32 | ))) |
