packages/lit-dev-content/site/tutorials/content/svg-templates/01.md
This section of the tutorial covers the basics of using SVG with Lit including how to:
In pattern making, an element refers to the smallest piece of a pattern that cannot be derived from other parts of the pattern.
The element in this demo will be a single piece of text. We can create text in SVG and Lit with SVG templates as demonstrated below.
const helloSVG = svg`<text>Hello, SVG!</text>`;
In Lit, an SVG template must be the child of an <svg> element. The
<svg> element must be contained inside an HTML template.
An implementation of these requirements is demonstrated by the following
example.
const helloHTML = html`
<svg>
${svg`<text>Hello, SVG!</text>`}
</svg>
`;
Create a function called createElement that generates a <text>
element with configurable display text using a Lit SVG template.
Add text-specfic styling attributes
to the <text> element.
{% switchable-sample %}
const createElement = (chars: string): SVGTemplateResult => svg`
<text
dominant-baseline="hanging"
font-family="monospace"
font-size="24px">
${chars}
</text>
`;
const createElement = (chars) => svg`
<text
dominant-baseline="hanging"
font-family="monospace"
font-size="24px">
${chars}
</text>
`;
{% endswitchable-sample %}
Call createElement in the render() function of a repeat-pattern
component similar to the example below.
{% switchable-sample %}
@customElement('repeat-pattern')
export class RepeatPattern extends LitElement {
render() {
return html`
<svg height="100%" width="100%">
${createElement("lit")}
</svg>
`;
}
}
import { LitElement } from "lit";
export class RepeatPattern extends LitElement {
render() {
return html`
<svg height="100%" width="100%">
${createElement("lit")}
</svg>
`;
}
}
customElements.define('repeat-pattern', RepeatPattern);
{% endswitchable-sample %}
Finally, create a reactive property called chars so that text
rendered can be configured by consumers of repeat-pattern.
{% switchable-sample %}
@customElement('repeat-pattern')
export class RepeatPattern extends LitElement {
@property({type: String}) chars = "lit";
render() {
return html`
<svg height="100%" width="100%">
${createElement(this.chars)}
</svg>
`;
}
}
export class RepeatPattern extends LitElement {
static properties = {
chars: {type: String},
};
constructor() {
super();
this.chars = 'lit';
}
render() {
return html`
<svg height="100%" width="100%">
${createElement(this.chars)}
</svg>
`;
}
}
customElements.define('repeat-pattern', RepeatPattern);
{% endswitchable-sample %}
After completing this section, you'll be ready to learn how to create reusable structures in SVG in the next chapter.