Skip to content

Dynamic SVG Templating

The approach of using a dynamic SVG template brings together the power of Scalable Vector Graphic (SVG), which is a declarative language, with the use of directives to instruct how the graphic should be constructed from the data. The SVG format is enhanced by way of attribute-based directives which create a more intuitive way of generating visual graphics. By using these directives, one can focus more on the design and data without the need to get into complex development.

Here are some of the main directives used:

  • g-bind: (or its shorthand version :): This directive is used to bind values to attribute dynamically.
  • g-for: This directive allows the block element to be rendered multiple times based on the given data.
  • g-if: With this, an element can be shown conditionally.
  • g-content: This directive is used to update the content of an element.

Here is an example to better understand their use. In this example, instead of creating three separate circle tags, the g-for directive is used in a defs element to generate the three circles dynamically. This is a simple example demonstrating the basic operational understanding of the SVG template model and directives.

In the following, we will describe how it works each directive:

g-bind:

The g-bind: directive, or the abbreviation :, followed by an attribute name, dynamically binds data values to attributes. That is, it assigns a value to an attribute dynamically.

In this example, the circle radius (r attribute) is defined with size data value with g-bind:r="size". When we change the value of the slider, the data.size value of the component is updated and the change is reflected in the chart.

See more about g-bind

g-for

Renders a block defined with the defs tag multiple times depending on the data. The directive dynamically evaluates a case of value or (case, index) of value expression. Value can be a number or an array.

In this example, a number of circles is displayed.

In this example, a set of circles are displayed. As many circles will be shown as the circles value has.

See more about g-for

g-if

Show or hide an element conditionally by an expression based on the data.

In this example, the odd and even circles are displayed if the values odd and event are true or false. The values are modified by two checkboxes that update the data property of g-composer.

See more about g-if.

g-content

Include data values as the element content. This attribute allows you to dynamically include text or code snippets very easily.

In this example, the text content is defined with title and subtitle data values. They are dynamically updated by two inputs.

See more about g-content.

Released under the MIT License.