Skip to content

Basic Templating

Leaf UI provides a simple templating system that allows you to render dynamic content in your views. This template system is a mix of Laravel's Blade templating system and LiveView's view system.

Displaying Data

To display data in your component, you may use the syntax. This syntax will be replaced with the value of the $var variable when the component is rendered:

<div>
    <h1>{{ $title }}</h1>
    <p>{{ $description }}</p>
</div>

Evaluating PHP

If you quickly want evaluate PHP expressions within your template, you can use the $eval function. This function will evaluate the given PHP expression and return the result:

<button @click="doSomething($eval($data + 1))">Hello</button>

You may also evaluate PHP code within your component using the @php and @endphp directives:

@php
    $title = "Hello World";

    if (count($users) > 0) {
        $title = "Hello Users";
    }
@endphp

If Statements

You may construct if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts:

@if (count($users) === 1)
    I have one record!
@elseif (count($users) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

Code breaks

Leaf UIs templates are directly executed at runtime. This may lead to unstable @elseif and @else statements. If you are using these statements, it is recommended that you use the @if directive instead. If you face any problems, please open an issue on GitHub.

Loops

In addition to conditional statements, Leaf UI provides simple directives for working with PHP's loop structures. Let's take a look at looping through a collection of users:

@loop($users)
<div>This will loop a couple of times</div>
@endloop

The @loop directive accepts a collection of data and will loop through each item in the collection. Sometimes you may need to access the current iteration of the loop. You may do so using the @key and @value directives:

@loop($users)
<div>The current key is @key and the current user is @value["name"]</div>
@endloop

Including Views

Views are just pieces of markup used/returned in components. Just like their components, individual views can themselves be included inside another component. This makes it easier to build dynamic UIs that can be reused across multiple components without having to worry about component logic.

Just as you can include whole components in your current component using the @component directive, you can also include created views using the @include directive.

@include("banner.html")
<main>
    @include("sidebar.html")
    <div class="content">
        ...
    </div>
</main>
Basic Templating has loaded