Let's explore the various WebStencils keywords with examples:
Comments in WebStencils are enclosed in @* *@ and are omitted from the resulting HTML.
@* This is a comment and will not appear in the output *@
<p>This will appear in the output</p>
Conditional execution is handled with @if and @else.
@if user.isLoggedIn {
<p>Welcome, @user.name!</p>
}
@else {
<p>Please log in to continue.</p>
}
For negative conditional execution, use @if not.
@if not cart.isEmpty {
<p>You have @cart.itemCount items in your cart.</p>
}
@else {
<p>Your cart is empty.</p>
}
The @switch operator allows you to execute different code blocks based on the value of an expression, providing a more readable alternative to multiple if-else statements.
@switch(status.id) {
@case 0 {
<span class="status-active">active</span>
} @case 1 {
<span class="status-inactive">inactive</span>
} @case 2 {
<span class="status-pending">pending</span>
} @default {
<span class="status-unknown">unknown</span>
}
}
The @ForEach keyword is used for iteration over elements in an enumerator.
<ul>
@ForEach (var product in productList) {
<li>@product.name - @product.price</li>
}
</ul>
The @query keyword is used to read HTTP query parameters. In this example, searchTerm
would be a parameter included in the URL: yourdomain.com?searchTerm="mySearch"
<p>You searched for: @query.searchTerm</p>
The @page keyword allows accesing multiple properties from the page as well as access connection.
<p>Current page is: @page.pagename</p>