Text Wrapping in a Node Template (version 1.x)
Tips & TricksSummary
Description
This post assumes that you are already familiar with Template Styles and Data Binding.
Motivation
Sometimes you might want to include text in your node template. In some cases, the text can exceed the node bounds without being cropped at the node boundaries. In this case you can take this approach to include line wrapping like SimpleLabelStyle in your node template.
An alternative is to write a custom node style as demonstrated in the Custom Styles Tutorial.
Code Example
Include a <g> element in your node template that binds data-content to item, using a template binding. Add a Converter argument that specified the path to the converter you're about to create.
<script type="text/yfiles-template">
<g id="NodeTemplate">
<rect stroke="none" fill="lightblue" rx="4" ry="4"
width="{TemplateBinding width}" height="{TemplateBinding height}"></rect>
<g data-content="{TemplateBinding item, Converter=converters.wrappingTextConverter}"></g>
</g>
</script>
Specify the Converter function somewhere in JavaScript code. The function gets the text to be rendered from the node tag. This sample uses node.tag.label.
<script type="text/javascript">
// get the node text from the object stored in the node tag
function getNodeText(nodeTag) {
// adjust this to your likes to get your data
return nodeTag.label;
}
var renderSupport = null;
// create an object to store the converter functions
var store = window.converters = {}
// the converter for the node text
store.wrappingTextConverter = function(value, parameter) {
var node = /**@type {yfiles.graph.INode}*/ value;
if (!node.tag) {
return "";
}
var text = getNodeText(node.tag);
// create the typeface which determines the visual text properties
var typeface = new yfiles.system.Typeface();
// create the text DOM element
var textElement = window.document.createElementNS("http://www.w3.org/2000/svg", "text");
textElement.setAttribute("fill", "black");
// assign the Typeface
yfiles.canvas.SVGExtensions.setTypeface(textElement, typeface);
// initialize TextRenderSupport if necessary
if (renderSupport == null) {
renderSupport = new yfiles.drawing.TextRenderSupport();
}
// do the text wrapping
// this sample uses the strategy ELLIPSIS_CHARAKTER. You can use any other setting
renderSupport.placeText(textElement, text, typeface, node.layout.toSize(), yfiles.system.StringTrimming.ELLIPSIS_CHARACTER);
return textElement;
}
</script>
Adjust the Typeface and StringTrimming used in the sample to your likes.