Views in BowPHP
- Introduction
- Configuration
- Creating a view
- Tintin Introduction
- Inheritance with #extends, #block and #inject
- Custom directive
- IDE support
- Additional package
- Is something missing?
Introductionβ
Views contain the HTML served by your application and separate your controller/application logic from your presentation logic:
Configurationβ
BowPHP implements 2 template engines and the default template engine is Tintin.
The view configuration is located in the view.php file in the config/ folder.
Specify the name of the template engine to use with the engine option in the configuration; this option can take the following values: tintin, twig and php. By default Bow uses tintin.
Note that if you set
php, views will be rendered without a template engine
You can also change the template extension by modifying the value of the extension entry. You will also notice that views are stored in the templates directory by default.
Creating a viewβ
A simple view can look like this
<!-- View stored in templates/greeting.tintin.php -->
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
After editing and saving your view in templates/greeting.tintin.php, you can now send it to users with the view helper like this:
$app->get('/', function() {
return view('greeting', ['name' => 'Tintin']);
});
Usageβ
Usage example: (With the View class)
This uses the parse method.
View::parse(view, data, status)
| Parameter | type | description |
|---|---|---|
view | String | The path of the view, knowing that the engine bases it on the views folder |
data | Array, Object | The data to pass to the view |
status | Integer | The http status code |
use Bow\View\View;
echo View::parse('nom-de-la-vue-sans-extension');
To pass variables to the view
use Bow\View\View;
echo View::parse(
'nom-de-la-vue-sans-extension',
['name' => 'bow'],
200
);
You can use the
viewhelper, which is used in the same way.
With the following view:
<!-- View stored in templates/greeting.tintin.php -->
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
Example in a controller:
namespace App\Controllers;
use App\Controllers\Controller;
class HomeController extends Controller
{
/**
* Show hello page
*
* @return mixed
*/
public function show()
{
return view('greeting', ['name' => 'Bowphp']);
// Or
return $this->render('greeting', ['name' => "Bowphp"]);
// Or
return response()->render('greeting', ['name' => "Bowphp"]);
}
}
Tintin Introductionβ
Tintin is a PHP template engine that aims to be very simple and extensible. It can be used in any PHP project. By default #Tintin is the template engine that BowPHP uses.
Tintin Configurationβ
You will find the configuration in the config/view.php file, and it is in the templates folder that template files are saved with the .tintin.php extension.
Displaying dataβ
You can display the content of the name variable as follows:
Hello, {{ $name }}.
Of course, you are not limited to displaying the content of the variables passed to the view. You can also echo the results of any PHP function. In fact, you can put any PHP code you wish inside a Blade echo statement:
Hello, {{ strtoupper($name) }}.
Tintin
{{ }}statements are automatically sent through the PHPhtmlspecialcharsfunction to prevent XSS attacks.
Displaying unescaped dataβ
By default, Tintin {{ }} statements are automatically sent through the PHP htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you can use the following syntax:
Hello, {{{ $name }}}.
Adding a commentβ
The {# comments #} clause lets you add a comment to your tintin code.
#if / #elseif or #elif / #elseβ
These are the clauses that let you set up conditional branching as in most programming languages.
<p>
#if ($name == 'tintin')
{{ $name }}
#elseif ($name == 'template')
{{ $name }}
#else
{{ $name }}
#endif
</p>
You can use
#elifinstead of#elseif.
#unlessβ
A small specificity: #unless lets you make a condition that is the inverse of #if.
To put it simply, here is an example:
#unless ($name == 'tintin')
// Equal to
#if (!($name == 'tintin'))
#loop / #for / #whileβ
Often you may need to build lists or repeat over elements. For example, displaying all the users of your platform.
Using #loopβ
This clause does exactly the same as foreach.
#loop ($names as $name)
Bonjour {{ $name }}
#endloop
This clause can also be combined with any other clause such as #if. Here is a quick example:
#loop ($names as $name)
#if ($name == 'tintin')
Bonjour {{ $name }}
#stop
#endif
#endloop
You may have noticed #stop; it lets you stop the execution of the loop. There is also its counterpart #jump, which stops execution at its point and starts the next iteration of the loop.
The #jump and #stop syntactic sugarβ
Often the developer needs to write stop conditions for the #loop loop like this:
#loop ($names as $name)
#if ($name == 'tintin')
#stop
// Or
#jump
#endif
#endloop
With the syntactic sugar, we can reduce the code like this:
#loop ($names as $name)
#stop($name == 'tintin')
// Or
#jump($name == 'tintin')
#endloop
Using #forβ
This clause does exactly the same as for.
#for ($i = 0; $i < 10; $i++)
// ..
#endfor
Using #whileβ
This clause does exactly the same as while.
#while ($name != 'tintin')
// ..
#endwhile
Including a fileβ
Often when you develop your code, you need to split up your application's views to be more flexible and write less code.
#include lets you include another template file within another.
#include('filename', data)
Inclusion exampleβ
Consider the following hello.tintin.php file:
Hello {{ $name }}
Usage:
#include('hello', ['name' => 'Tintin'])
// => Hello Tintin
Inheritance with #extends, #block and #injectβ
Like any good template system, tintin supports sharing code between files. This makes your code flexible and maintainable.
Consider the following tintin code:
// the `layout.tintin.php` file
<!DOCTYPE html>
<html>
<head>
<title>Hello, world</title>
</head>
<body>
<h1>Page header</h1>
<div id="page-content">
#inject('content')
</div>
<p>Page footer</p>
</body>
</html>
And we also have another file that inherits the code from the layout.tintin.php file
// the file is named `content.tintin.php`
#extends('layout')
#block('content')
<p>This is the page content</p>
#endblock
Explanationβ
The content.tintin.php file will inherit the code from layout.tintin.php, and if you look closely, in the layout.tintin.php file we have the #inject clause whose parameter is the name of the #block from content.tintin.php, which is content. This means that the content of the content #block will be substituted in place of #inject. Which ultimately gives this:
<!DOCTYPE html>
<html>
<head>
<title>Hello, world</title>
</head>
<body>
<h1>Page header</h1>
<div id="page-content">
<p>This is the page content</p>
</div>
<p>Page footer</p>
</body>
</html>
Custom directiveβ
Tintin can be extended with its custom directive system; to do this use the directive method. To achieve this we created a configuration and extended the native configuration \Tintin\Bow\TintinConfiguration::class.
php bow add:configuration TintinConfiguration
Adding your directives from the configurationβ
After creating the configuration you will find the app/Configurations/TintinConfiguration.php file, which will extend Tintin's default configuration \Tintin\Bow\TintinConfiguration::class, and then modify the onRunning method.
use Tintin\Tintin;
class TintinConfiguration extends \Tintin\Bow\TintinConfiguration
{
/**
* Add action in tintin
*
* @param Tintin $tintin
*/
public function onRunning(Tintin $tintin)
{
$tintin->directive('super', function (array $attributes = []) {
return "Super !";
});
}
}
To finish in style, replace Tintin's default configuration in app/Kernel.php with App/Configurations/TintinConfiguration::class.
Now the #super directive is available and you can use it.
return $tintin->render('#super');
// => Super !
Directive creation exampleβ
Let's add a simple directive. We will call it #hello
$tintin->directive('hello', function (array $attributes = []) {
return 'Hello, '. $attributes[0];
});
echo $tintin->render('#hello("Tintin")');
// => Hello, Tintin
Creating directives to handle a form:
$tintin->directive('input', function (array $attributes = []) {
$attribute = $attributes[0];
return '<input type="'.$attribute['type'].'" name="'.$attribute['name'].'" value="'.$attribute['value'].'" />';
});
$tintin->directive('textarea', function (array $attributes = []) {
$attribute = $attributes[0];
return '<textarea name="'.$attribute['name'].'">"'.$attribute['value'].'"</textarea>';
});
$tintin->directive('button', function (array $attributes = []) {
$attribute = $attributes[0];
return '<button type="'.$attribute['type'].'">'.$attribute['label'].'"</button>';
});
$tintin->directive('form', function (array $attributes = []) {
$attribute = " ";
if (isset($attributes[0])) {
foreach ($attributes[0] as $key => $value) {
$attribute .= $key . '="'.$value.'" ';
}
}
return '<form "'.trim($attribute).'">';
});
$tintin->directive('endform', function (array $attributes = []) {
return '</form>';
});
Using directivesβ
Using these directives could not be simpler. Write the name of the directive preceded by #. Then if that directive takes parameters, call the directive the way you call functions in your program. The parameters will be grouped into the $attributes variable in the order they were added.
/** form.tintin.php file **/
#form(['method' => 'post', "action" => "/posts", "enctype" => "multipart/form-data"])
#input(["type" => "text", "value" => null, "name" => "name"])
#textarea(["value" => null, "name" => "content"])
#button(['type' => 'submit', 'label' => 'Add'])
#endform
Compiling the templateβ
Compilation is done as usual; for more information on compilation.
echo $tintin->render('form');
Output after compilationβ
<form action="/posts" method="post" enctype="multipart/form-data">
<input type="text" name="name" value="" />
<textarea name="content"></textarea>
<button type="submit">Add</button>
</form>
IDE supportβ
Tintin is currently supported by sublime text.
How to install Sublime Package Controlβ
Go to the site and follow the instructions.
Installing the Tintin packageβ
- Search for Bow Tintin and install it / Download or clone this repository into [install-dir]/Packages/bow-tintin
- Restart Sublime Text.
- Reopen any
.tintinor.tintin.phpfile. - Enjoy π
Additional packageβ
In case you have opted for the twig template engine, here is the list of the twig package:
| Template | Package |
|---|---|
| Twig | twig/twig |
Installing twigβ
composer require twig/twig
View with Twigβ
Twig is a template engine for the PHP programming language, used by default by the Symfony Framework.
It is said to have been inspired by Jinja, the Python template engine used in Django.
Code example:
$names = [
"resque", "hub", "rip"
];
{# templates/greeting.twig #}
<html>
<body>
<h1>Hello, User</h1>
{% for name in names %}
<p>Hello, {{name}}</p>
{% endfor %}
</body>
</html>
Is something missing?
If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.