Description: The x-text directive in AlpineJS allows you to display reactive data from your x-data component's scope as the text content of an HTML element. This text content updates automatically whenever the underlying data changes. For Python developers familiar with Django or Flask, this is conceptually similar to using template variables like {{ my_variable }}, but it happens entirely on the client-side, powered by JavaScript, making your UI dynamic without page reloads.
x-text is an AlpineJS directive that you add to an HTML element. Its value can be either a property name from your component's data scope or a valid JavaScript expression.
x-text="propertyName"
This is the most common usage. You bind x-text directly to a property name defined in your x-data object. Alpine.js will then take the value of this property and set it as the textContent of the HTML element. If the property's value changes, the displayed text will update reactively.
<div x-data="{ message: 'Hello Alpine!' }">
<span x-text="message"></span> <!-- Output: Hello Alpine! -->
</div>
x-text="'Hello, ' + name" (JavaScript expressions)
You can provide any valid JavaScript expression as the value for x-text. This allows for more complex dynamic text generation, such as concatenating strings, performing calculations, calling component methods, or using JavaScript's built-in functions. When using literal strings within the expression, remember to enclose them in quotes (single ' or double ").
<div x-data="{ name: 'User', score: 100, isActive: true }">
<p x-text="'Welcome, ' + name + '!'"></p> <!-- Output: Welcome, User! -->
<p x-text="'Your score: ' + (score * 2)"></p> <!-- Output: Your score: 200 -->
<p x-text="isActive ? 'Status: Active' : 'Status: Inactive'"></p> <!-- Output: Status: Active -->
</div>
Trying to render HTML with x-text.
x-text sets the textContent property of an element. This means any HTML tags (e.g., <strong>, <em>) within the data you're displaying will be treated as literal text and will appear as such on the page, not rendered as HTML elements. This is an important security feature that helps prevent Cross-Site Scripting (XSS) vulnerabilities by default.
<div x-data="{ myHtml: '<strong>Important!</strong>' }">
<p x-text="myHtml"></p>
<!-- Output: <strong>Important!</strong> (displayed as this literal string) -->
</div>
If you explicitly need to render HTML from a data property, and you understand and have mitigated the security risks (i.e., the HTML source is trusted or sanitized), you should use the x-html directive instead.
Forgetting quotes for literal strings in expressions.
When combining reactive data with static text within an x-text expression, JavaScript's string concatenation rules apply. Literal strings must be enclosed in quotes (single ' or double "). If you forget the quotes, JavaScript will attempt to interpret the static text as a variable name. If no such variable exists, it will typically result in an error or undefined behavior.
<div x-data="{ username: 'Alice' }">
<!-- Correct: -->
<p x-text="'User: ' + username"></p> <!-- Output: User: Alice -->
<!-- Incorrect (JavaScript will look for a variable named `User`): -->
<!-- <p x-text="User: + username"></p> --> <!-- This will likely cause an error -->
</div>
Python developers can relate this to how string literals are defined in Python – they always require quotes.
Assuming x-text automatically formats data.
x-text displays data "as is" from your component's properties or the result of your JavaScript expression. It does not perform any automatic formatting for data types like dates or numbers (e.g., adding currency symbols, thousand separators, or converting a Date object to a specific string format).
If you need to format data, you should handle it explicitly:
x-data methods or getters: Create a method or a JavaScript getter in your x-data component that returns the data in the desired formatted string. This is often the cleanest approach for complex formatting.x-text expression: Call JavaScript's built-in formatting functions (e.g., Date.prototype.toLocaleDateString(), Number.prototype.toFixed()) or custom utility functions directly within the expression.<div x-data="{
eventDate: new Date(2024, 11, 25), // Christmas 2024
itemPrice: 29.9935,
get formattedEventDate() {
return this.eventDate.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
}
}">
<p>Raw Date (via .toString()): <span x-text="eventDate.toString()"></span></p>
<p>Formatted Date (via getter): <span x-text="formattedEventDate"></span></p>
<p>Price (JS in expression): <span x-text="'Price: $' + itemPrice.toFixed(2)"></span></p> <!-- Output: Price: $29.99 -->
</div>
Directly bound name:
Greeting (JS expression):
Current Date/Time (raw):
Formatted Date/Time (computed property):
Component data htmlContent holds:
Attempting to render with x-text:
(Notice above how '<b>Bold Text</b>' is shown as a literal string, not as bolded HTML text. Use x-html for rendering HTML, with caution.)