x-text and x-html
To show a component's data, you output it into an element. The x-text directive writes the value of an expression into the element's text, and x-html writes it into the element's HTML markup. Both update the element as soon as the data changes.
x-text
The value of x-text is any JavaScript expression. The result becomes the element's content, just like writing to textContent:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ task: 'Buy milk' }">
<p x-text="task"></p>
</div>The paragraph shows "Buy milk". If the <p> contained other text, Alpine replaces it.
Expressions
Inside x-text you can do math, join strings, call methods and use the ternary operator:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ tasks: ['Buy milk', 'Call Oleg'], done: 1 }">
<p x-text="`Done ${done} of ${tasks.length}`"></p>
<p x-text="tasks[0].toUpperCase()"></p>
<p x-text="done === tasks.length ? 'All done' : 'Work to do'"></p>
</div>The page shows three lines: "Done 1 of 2", "BUY MILK" and "Work to do". Move long logic into a component method or getter to keep the markup readable.
x-html
The x-html directive inserts a string as markup — tags in it become real elements:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ note: 'Due <b>today</b>' }">
<p x-html="note"></p>
</div>The word "today" is shown in bold. With x-text the page would show the <b> characters themselves.
Which to choose
| Directive | How it outputs | When to use |
|---|---|---|
x-text | As text, tags do nothing | Almost always |
x-html | As markup | Only for HTML written by you or your server |
Common mistake
Outputting text typed by a user with x-html. Along with the text, someone else's code gets onto the page — the XSS vulnerability from the "Changing the page" lesson of the tutorial:
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<div x-data="{ comment: '<img src=x onerror=console.log(1)>' }">
<p x-text="comment"></p>
</div>With x-text the string is shown as is and nothing runs. Replace x-text with x-html and the console prints 1: the code from the "comment" ran. Use only x-text for user data.