edit

Oxygen Templates

Introduction

Oxygen is the simple, yet powerful templating engine provided with Skytells Framework. Unlike other popular PHP templating engines, Oxygen does not restrict you from using plain PHP code in your views. In fact, all Oxygen views are compiled into plain PHP code and cached until they are modified, meaning Oxygen adds essentially zero overhead to your application. Oxygen view files use the .ui.php file extension and are typically stored in the Application/Resources/Views directory.

Initialization

This Engine is not REQUIRED to run your MVC project based on Skytells Framework. So, you need to import the engine when needed.

Engine Loaded by Default

This engine is included in the standard Framework library. So it doesn't need to be loaded in your controller using the engine loader.

Configuration

Please make sure to add the right configuration in order to use this template engine.

Configuration

If you have not configured the Template Engines's settings file
Please Click here to learn more

This Engine is set to be the default Template engine! If you'd change it before, Please make sure of your settings.

Lets move, Go to the Templates Configuration File Listed in :

1
Application/Misc/Config/Templates.php

You need to change the TEMPLATE_ENGINE option to MicroUI. to be like :

1
  $Settings["TEMPLATE_ENGINE"] = "Oxygen"; // Warning (Case-Sensitive)

Now, The Framework is defined the Oxygen as your default Template Engine.

Template Inheritance

Defining A Layout

Two of the primary benefits of using Oxygen are template inheritance and sections. To get started, let's take a look at a simple example. First, we will examine a "master" page layout. Since most web applications maintain the same general layout across various pages, it's convenient to define this layout as a single Oxygen view:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!-- Stored in application/resources/views/layouts/app.ui.php -->

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

As you can see, this file contains typical HTML mark-up. However, take note of the @section and @yield directives. The @section directive, as the name implies, defines a section of content, while the @yield directive is used to display the contents of a given section.

Now that we have defined a layout for our application, let's define a child page that inherits the layout.

Extending A Layout

When defining a child view, use the Oxygen @extends directive to specify which layout the child view should "inherit". Views which extend a Oxygen layout may inject content into the layout's sections using @section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using @yield:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!-- Stored in Application/Resources/Views/child.ui.php -->

    @extends('layouts.app')

    @section('title', 'Page Title')

    @section('sidebar')
        @parent

        <p>This is appended to the master sidebar.</p>
    @endsection

    @section('content')
        <p>This is my body content.</p>
    @endsection

In this example, the sidebar section is utilizing the @parent directive to append (rather than overwriting) content to the layout's sidebar. The @parent directive will be replaced by the content of the layout when the view is rendered.

Oxygen views may be returned from routes using the global view helper:

1
2
3
Route::get('Oxygen', function () {
    return view('child');
});

Components & Slots

Components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. First, let's imagine a reusable "alert" component we would like to reuse throughout our application:

1
2
3
4
5
    <!-- /resources/views/alert.ui.php -->

    <div class="alert alert-danger">
        {{ $slot }}
    </div>

The {{$slot}} variable will contain the content we wish to inject into the component. Now, to construct this component, we can use the @component Oxygen directive:

1
2
3
    @component('alert')
        <strong>Whoops!</strong> Something went wrong!
    @endcomponent

Sometimes it is helpful to define multiple slots for a component. Let's modify our alert component to allow for the injection of a "title". Named slots may be displayed by simply "echoing" the variable that matches their name:

1
2
3
4
5
6
7
    <!-- /resources/views/alert.ui.php -->

    <div class="alert alert-danger">
        <div class="alert-title">{{ $title }}</div>

        {{ $slot }}
    </div>

Now, we can inject content into the named slot using the @slot directive. Any content not within a @slot directive will be passed to the component in the $slot variable:

1
2
3
4
5
6
7
    @component('alert')
        @slot('title')
            Forbidden
        @endslot

        You are not allowed to access this resource!
    @endcomponent

Passing Additional Data To Components

Sometimes you may need to pass additional data to a component. For this reason, you can pass an array of data as the second argument to the @component directive. All of the data will be made available to the component template as variables:

1
2
3
@component('alert', ['foo' => 'bar'])
    ...
@endcomponent

Displaying Data

You may display data passed to your Oxygen views by wrapping the variable in curly braces. So, In your controller, you must bypass the var array.

1
2
<?php
View::render("myfile.ui.php", null, null, Array("name" => "Hazem"));

You may display the contents of the name variable like so:

1
    Hello, {{ $name }}.

Of course, you are not limited to displaying the contents of the variables passed to the view. You may also echo the results of any PHP function. In fact, you can put any PHP code you wish inside of a Oxygen echo statement:

1
The current UNIX timestamp is {{ time() }}.

Tip

Oxygen {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks.

Echoing Data If It Exists

Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. We can express this in verbose PHP code like so:

1
{{ isset($name) ? $name : 'Default' }}

However, instead of writing a ternary statement, Oxygen provides you with the following convenient shortcut, which will be compiled to the ternary statement above:

1
{{ $name or 'Default' }}

In this example, if the $name variable exists, its value will be displayed. However, if it does not exist, the word Default will be displayed.

Displaying Unescaped Data

By default, Oxygen {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

1
Hello, {!! $name !!}.

Careful!

Be very careful when echoing content that is supplied by users of your application. Always use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

Oxygen & JavaScript Frameworks

Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Oxygen rendering engine an expression should remain untouched. For example:

1
2
3
<h1>Skytells Framework</h1>

Hello, @{{ name }}.

In this example, the @ symbol will be removed by Oxygen; however, {{ name }} expression will remain untouched by the Oxygen engine, allowing it to instead be rendered by your JavaScript framework.

The @verbatim Directive

If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the @verbatim directive so that you do not have to prefix each Oxygen echo statement with an @ symbol:

1
2
3
4
5
@verbatim
    <div class="container">
        Hello, {{ name }}.
    </div>
@endverbatim

Control Structures

In addition to template inheritance and displaying data, Oxygen also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts.

If Statements

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

1
2
3
4
5
6
7
@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

For convenience, Oxygen also provides an @unless directive:

1
2
3
@unless (Auth::check())
    You are not signed in.
@endunless

Loops

In addition to conditional statements, Oxygen provides simple directives for working with PHP's loop structures. Again, each of these directives functions identically to their PHP counterparts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

@while (true)
    <p>I'm looping forever.</p>
@endwhile

When looping, you may use the loop variable to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop.

When using loops you may also end the loop or skip the current iteration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

You may also include the condition with the directive declaration in one line:

1
2
3
4
5
6
7
@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach

The Loop Variable

When looping, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

If you are in a nested loop, you may access the parent loop's $loop variable via the parent property:

1
2
3
4
5
6
7
@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

The $loop variable also contains a variety of other useful properties:

Property Description
`$loop->index` The index of the current loop iteration (starts at 0).
`$loop->iteration` The current loop iteration (starts at 1).
`$loop->remaining` The iteration remaining in the loop.
`$loop->count` The total number of items in the array being iterated.
`$loop->first` Whether this is the first iteration through the loop.
`$loop->last` Whether this is the last iteration through the loop.
`$loop->depth` The nesting level of the current loop.
`$loop->parent` When in a nested loop, the parent's loop variable.

Comments

Oxygen also allows you to define comments in your views. However, unlike HTML comments, Oxygen comments are not included in the HTML returned by your application:

1
{{-- This comment will not be present in the rendered HTML --}}

PHP

In some situations, it's useful to embed PHP code into your views. You can use the Oxygen @php directive to execute a block of plain PHP within your template:

1
2
3
@php
    //
@endphp

While Oxygen provides this feature, using it frequently may be a signal that you have too much logic embedded within your template.

Including Sub-Views

Oxygen's @include directive allows you to include a Oxygen view from within another view. All variables that are available to the parent view will be made available to the included view:

1
2
3
4
5
6
7
<div>
    @include('shared.errors')

    <form>
        <!-- Form Contents -->
    </form>
</div>

Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

1
@include('view.name', ['some' => 'data'])

Of course, if you attempt to @include a view which does not exist, Skytells Framework will throw an error. If you would like to include a view that may or may not be present, you should use the @includeIf directive:

1
@includeIf('view.name', ['some' => 'data'])

Warning

You should avoid using the __DIR__ and __FILE__ constants in your Oxygen views, since they will refer to the location of the cached, compiled view.

Rendering Views For Collections

You may combine loops and includes into one line with Oxygen's @each directive:

1
@each('view.name', $jobs, 'job')

The first argument is the view partial to render for each element in the array or collection. The second argument is the array or collection you wish to iterate over, while the third argument is the variable name that will be assigned to the current iteration within the view. So, for example, if you are iterating over an array of jobs, typically you will want to access each job as a job variable within your view partial. The key for the current iteration will be available as the key variable within your view partial.

You may also pass a fourth argument to the @each directive. This argument determines the view that will be rendered if the given array is empty.

1
@each('view.name', $jobs, 'job', 'view.empty')

Stacks

Oxygen allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views:

1
2
3
@push('scripts')
    <script src="/example.js"></script>
@endpush

You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the @stack directive:

1
2
3
4
5
<head>
    <!-- Head Contents -->

    @stack('scripts')
</head>

Service Injection

The @inject directive may be used to retrieve a service from the Skytells Framework service container. The first argument passed to @inject is the name of the variable the service will be placed into, while the second argument is the class or interface name of the service you wish to resolve:

1
2
3
4
5
@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

Extending Oxygen

Oxygen allows you to define your own custom directives using the directive method. When the Oxygen compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains.

The following example creates a @datetime($var) directive which formats a given $var, which should be an instance of DateTime:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php


    public function boot()
    {
        Oxygen::directive('datetime', function ($expression) {
            return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }

As you can see, we will chain the format method onto whatever expression is passed into the directive. So, in this example, the final PHP generated by this directive will be:

1
<?php echo ($var)->format('m/d/Y H:i'); ?>

After updating the logic of a Oxygen directive, you will need to delete all of the cached Oxygen views. The cached Oxygen views may be removed using the ?action=flushcache GET Parameter.