Package Data | |
---|---|
Maintainer Username: | JorgeCastro |
Maintainer Contact: | jcastro@eftec.cl (Jorge Patricio Castro Castillo) |
Package Create Date: | 2016-06-08 |
Package Last Update: | 2024-10-11 |
Home Page: | https://www.escuelainformatica.cl/ |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-12 15:03:41 |
Package Statistics | |
---|---|
Total Downloads: | 4,353,626 |
Monthly Downloads: | 187,852 |
Daily Downloads: | 9,332 |
Total Stars: | 779 |
Total Watchers: | 23 |
Total Forks: | 120 |
Total Open Issues: | 15 |
BladeOne is a standalone version of Blade Template Engine that uses a single PHP file and can be ported and used in different projects. It allows you to use blade template outside Laravel.
Бладеоне-это отдельная версия ядра Blade-шаблонов, которая использует один PHP-файл и может быть портирована и использована в различных проектах. Он позволяет использовать шаблон Blade за пределами laravel.
NOTE: So far it's apparently the only one project that it's updated with the latest version of Blade 5.8 (December 2019). It misses some commands missing but nothing more.
Примечание: до сих пор это, видимо, только один проект, который обновляется с последней версией ** Blade 5,8 (2019 января) **. Он пропускает некоторые команды отсутствует, но ничего больше.
You can find some tutorials and example on the folder Examples.
By standard, The original Blade library is part of Laravel (Illuminate components) and to use this template library, you require to install Laravel and Illuminate-view components. The syntax of Blade is pretty nice and bright. It's based in C# Razor (another template library for C#). It's starting to be considered a de-facto standard template system for many PHP (Smarty has been riding off the sunset since years ago) so, if we can use it without Laravel then its a big plus for many projects. In fact, in theory, it is even possible to use with Laravel. Exists different version of Blade Template that runs without Laravel but most requires 50 or more files and those templates add a new level of complexity, so they are not removing Laravel but hiding:
This project uses a single file called BladeOne.php and a single class (called BladeOne). If you want to use it then include it, creates the folders and that's it!. Nothing more (not even namespaces)*[]: It is also possible to use Blade even with Laravel or any other framework. After all, BladeOne is native, so it's possible to integrate into almost any project.
Let’s say that we have the next code
//some PHP code
// some HTML code
// more PHP code
// more HTML code.
It leads to a mess of a code. For example, let’s say that we oversee changing the visual layout of the page. In this case, we should change all the code and we could even break part of the programming.
Instead, using a template system works in the next way:
// some php code
ShowTemplate();
We are separating the visual layer from the code layer. As a plus, we could assign a non-php-programmer in charge to edit the template, and he/she doesn’t need to touch or know our php code.
Let’s say that we have the next exercise (it’s a dummy example)
$name=@$_GET['name'];
echo "my name is ".$name;
It could be separates as two files:
$name=@$_GET['name'];
include "template.php";
// template.php
echo "my name is ".$name;
Even for this simple example, there is a risk of hacking. How? A user could sends malicious code by using the GET variable, such as html or even javascript. The second file should be written as follow:
// template.php
echo "my name is ".html_entities($name);
html_entities should be used in every single part of the visual layer (html) where the user could injects malicious code, and it’s a real tedious work. BladeOne does it automatically.
// template.blade.php
My name is {{$name}}
BladeOne is focused on an easy syntax that it's fast to learn and to write, while it could keep the power of PHP.
Let's consider the next template:
<select>
<? foreach($countries as $c) { ?>
<option value=<? echo html_entities($c->value); ?> > <? echo html_entities($c->text); ?></option>
<? } ?>
</select>
With BladeOne, we could do the same with
<select>
@foreach($countries as $c)
<option value={{$c->value}} >{{echo html_entities($c->text)}}</option>
@nextforeach
</select>
And if we use thehtml extension we could even reduce to
@select('id1')
@items($countries,'value','text','','')
@endselect()
This library works in two stages.
The first is when the template is called the first time. In this case, the template is compiled and stored in a folder.
The second time the template is called then, it uses the compiled file. The compiled file consist mainly in native PHP, so the performance is equals than native code. since the compiled version IS PHP.
You could add and use your own function by adding a new method (or extending) to the BladeOne class. NOTE: The function should start with the name "compile"
protected function compileMyFunction($expression)
{
return $this->phpTag . "echo 'YAY MY FUNCTION IS WORKING'; ?>";
}
Where the function could be used in a template as follow
@myFunction('param','param2'...)
Alternatively, BladeOne allows to run arbitrary code from any class or method if its defined.
{{SomeClass::SomeMethod('param','param2'...)}}
example.php:
include "lib/BladeOne.php"; // you should change it and indicates the correct route.
Use eftec\bladeone;
$views = __DIR__ . '/views'; // it uses the folder /views to read the templates
$cache = __DIR__ . '/cache'; // it uses the folder /cache to compile the result.
$blade = new bladeone\BladeOne($views,$cache,BladeOne::MODE_AUTO);
echo $blade->run("hello",array("variable1"=>"value1")); // /views/hello.blade.php must exist
include "../lib/BladeOne.php";
// The nulls indicates the default folders. By drfault it's /views and /compiles
// \eftec\bladeone\BladeOne::MODE_DEBUG is useful because it indicates the correct file if the template fails to load.
// You must disable it in production.
$blade = new \eftec\bladeone\BladeOne(null,null,\eftec\bladeone\BladeOne::MODE_DEBUG);
echo $blade->run("Test.hello", []); // the template must be in /views/Test/hello.blade.php
require "vendor/autoload.php";
Use eftec\bladeone\BladeOne;
$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';
$blade = new BladeOne($views,$cache,BladeOne::MODE_AUTO);
echo $blade->run("hello",array("variable1"=>"value1"));
Run the next composer command:
composer require eftec/bladeone
Where $views
is the folder where the views (templates not compiled) will be stored.
$cache
is the folder where the compiled files will be stored.
In this example, the BladeOne opens the template hello. So in the views folder it should exist a file called hello.blade.php
views/hello.blade.php:
<h1>Title</h1>
{{$variable1}}
require "vendor/autoload.php";
Use eftec\bladeone;
$views = __DIR__ . '/views';
$cache = __DIR__ . '/cache';
$blade=new bladeone\BladeOne($views,$cache,BladeOne::MODE_AUTO);
$blade->setAuth('johndoe','admin'); // where johndoe is an user and admin is the role. The role is optional
echo $blade->run("hello",array("variable1"=>"value1"));
If you log in using blade then you could use the tags @auth/@endauth/@guest/@endguest
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
or
@auth('admin')
// The user is authenticated...
@endauth
@guest('admin')
// The user is not authenticated...
@endguest
$blade=new bladeone\BladeOne($views,$compile,$mode);
BladeOne(templatefolder,compiledfolder,$mode)
Creates the instance of BladeOne.Example:
$blade=new bladeone\BladeOne(__DIR__.'/views',__DIR__.'/compiles');
// or multiple views:
$blade=new bladeone\BladeOne([__DIR__.'/views',__DIR__.'/viewsextras'],__DIR__.'/compiles');
echo $blade->run("hello",array("variable1"=>"value1"));
echo $blade->share("global","valueglobal"));
echo $blade->run("hello",array("variable1"=>"value1"));
It adds a global variable
It sets the mode of compilation.
If the constant BLADEONE_MODE is defined, then it has priority over setMode()
|mode|behaviour| |---|---| |BladeOne::MODE_AUTO|Automatic, BladeOne checks the compiled version, if it is obsolete, then a new version is compiled and it replaces the old one| |BladeOne::MODE_SLOW|Slow, BladeOne always compile and replace with a new version. It is useful for development| |BladeOne::MODE_FAST|Fast, Bladeone never compile or replace the compiled version, even if it doesn't exist| |BladeOne::MODE_DEBUG| It's similar to MODE_SLOW but also generates a compiled file with the same name than the template.
It sets or gets the extension of the template file. By default, it's .blade.php
The extension includes the leading dot.
It sets or gets the extension of the template file. By default, it's .bladec
The extension includes the leading dot.
echo $blade->runString('<p>{{$direccion}}</p>', array('direccion'=>'cra 20 #33-58'));
It sets a new directive (command) that runs on compile time.
$blade->directive('datetime', function ($expression) {
return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
});
@datetime($now)
It sets a new directive (command) that runs on runtime time.
$blade->directiveRT('datetimert', function ($expression) {
echo $expression->format('m/d/Y H:i');
});
@datetimert($now)
It defines the mode of compilation (via global constant) See setMode(mode) for more information.
define("BLADEONE_MODE",BladeOne::MODE_AUTO);
BLADEONE_MODE
Is a global constant that defines the behaviour of the engine.$blade->setMode(BladeOne::MODE_AUTO);
|Tag|Note| |---|---| |@section('sidebar')|Start a new section| |@show|Indicates where the content of section will be displayed| |@yield('title')|Show here the content of a section|
|Tag|Note| |---|---| |@extends('layouts.master')|Indicates the layout to use| |@section('title', 'Page Title')|Sends a single text to a section| |@section('sidebar')|Start a block of code to send to a section| |@endsection|End a block of code|
Note :(*) This feature is in the original documentation but it's not implemented either is it required. Maybe it's an obsolete feature.
|Tag|Note| |---|---| |{{$variable1}}|show the value of the variable using htmlentities (avoid xss attacks)| |@{{$variable1}}|show the value of the content directly (not evaluated, useful for js)| |{!!$variable1!!}|show the value of the variable without htmlentities (no escaped)| |{{ $name or 'Default' }}|value or default| |{{Class::StaticFunction($variable)}}|call and show a function (the function should return a value)|
|Tag|Note| |---|---| |@if (boolean)|if logic-conditional| |@elseif (boolean)|else if logic-conditional| |@else|else logic| |@endif|end if logic| |@unless(boolean)|execute block of code is boolean is false|
Generates a loop until the condition is meet and the variable is incremented for each loop
|Tag|Note|Example|
|---|---|---|
|$variable|is a variable that should be initialized.|$i=0|
|$condition|is the condition that must be true, otherwise the cycle will end.|$i<10|
|$increment|is how the variable is incremented in each loop.|$i++|
Example:
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}<br>
@endfor
Returns:
The current value is 0
The current value is 1
The current value is 2
The current value is 3
The current value is 4
The current value is 5
The current value is 6
The current value is 7
The current value is 8
The current value is 9
@inject('metric', 'App\Services\MetricsService')
<div>
Monthly Revenue: {{ $metric->monthlyRevenue() }}.
</div>
By default, BladeOne creates a new instance of the class 'variable name'
inside 'namespace'
with the parameterless constructor.
To override the logic used to resolve injected classes, pass a function to setInjectResolver
.
Example with Symphony Dependency Injection.
$containerBuilder = new ContainerBuilder();
$loader = new XmlFileLoader($containerBuilder, new FileLocator(__DIR__));
$loader->load('services.xml');
$blade->setInjectResolver(function ($namespace, $variableName) use ($loader) {
return $loader->get($namespace);
});
Generates a loop for each values of the variable.
|Tag|Note|Example|
|---|---|---|
|$array|Is an array with values.|$countries|
|$alias|is a new variable that it stores each interaction of the cycle.|$country|
Example: ($users is an array of objects)
@foreach($users as $user)
This is user {{ $user->id }}
@endforeach
Returns:
This is user 1
This is user 2
Its the same as foreach but jumps to the @empty
tag if the array is null or empty
|Tag|Note|Example|
|---|---|---|
|$array|Is an array with values.|$countries|
|$alias|is a new variable that it stores each interaction of the cycle.|$country|
Example: ($users is an array of objects)
@forelse($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
Returns:
John Doe
Anna Smith
Loops until the condition is not meet.
|Tag|Note|Example| |---|---|---| |$condition|The cycle loops until the condition is false.|$counter<10|
Example: ($users is an array of objects)
@set($whilecounter=0)
@while($whilecounter<3)
@set($whilecounter)
I'm looping forever.<br>
@endwhile
Returns:
I'm looping forever.
I'm looping forever.
I'm looping forever.
This functions show a text inside a @foreach
cycle every "n" of elements. This function could be used when you want to add columns to a list of elements.
NOTE: The $textbetween
is not displayed if its the last element of the last. With the last element, it shows the variable $textend
|Tag|Note|Example|
|---|---|---|
|$nElem|Number of elements|2, for every 2 element the text is displayed|
|$textbetween|Text to show|</tr><tr>
|
|$textend|Text to show|</tr>
|
Example: ($users is an array of objects)
<table border="1">
<tr>
@foreach($drinks7 as $drink)
<td>{{$drink}}</td>
@splitforeach(2,'</tr><tr>','</tr>')
@endforeach
</table>
Returns a table with 2 columns.
Continue jump to the next iteration of a cycle. @break
jump out of a cycle.
|Tag|Note|Example| |---|---|---|
Example: ($users is an array of objects)
@foreach($users as $user)
@if($user->type == 1) // ignores the first user John Smith
@continue
@endif
<li>{{ $user->type }} - {{ $user->name }}</li>
@if($user->number == 5) // ends the cycle.
@break
@endif
@endforeach
Returns:
2 - Anna Smith
Example:(the indentation is not required)
@switch($countrySelected)
@case(1)
first country selected<br>
@break
@case(2)
second country selected<br>
@break
@defaultcase()
other country selected<br>
@endswitch()
@switch
The first value is the variable to evaluate.@case
Indicates the value to compare. It should be run inside a @switch/@endswitch@default
(optional) If not case is the correct then the block of @defaultcase is evaluated.@break
Break the case@endswitch
End the switch.|Tag|Note| |---|---| |@include('folder.template')|Include a template| |@include('folder.template',['some' => 'data'])|Include a template with new variables| |@each('view.name', $array, 'variable')|Includes a template for each element of the array| Note: Templates called folder.template is equals to folder/template
It includes a template
You could include a template as follow:
<div>
@include('shared.errors')
<form>
<!-- Form Contents -->
</form>
</div>
You could also pass parameters to the template
@include('view.name', ['some' => 'data'])
Additionally, if the template doesn't exist then it will fail. You could avoid it by using includeif
@includeIf('view.name', ['some' => 'data'])
@Includefast
is similar to @include
. However, it doesn't allow parameters because it merges the template in a big file (instead of relying on different files), so it must be fast at runtime by using more space on the hard disk versus less call to read a file.
@includefast('view.name')
This template runs at compile time, so it doesn't work with runtime features such as @if() @includefast() @endif()
Laravel's blade allows to create aliasing include. Laravel calls this method "include()". However, PHP 5.x doesn't allow to use the name "include()" so in this library is called "addInclude()".
How it work?
If your BladeOne includes are stored in a sub-directory, you may wish to alias them for easier access. For example, imagine a BladeOne include that is stored at views/includes/input.blade.php with the following content:
📁 views/includes/input.blade.php
<input type="{{ $type ?? 'text' }}">
You may use the include method to alias the include from includes.input to input.
Blade->addInclude('includes.input', 'input');
Once the include has been aliased, you may render it using the alias name as the Blade directive:
@input(['type' => 'email'])
|Tag|Note| |---|---| |{{-- text --}}|Include a comment|
|Tag|Note| |---|---| |@push('elem')|Add the next block to the push stack| |@endpush|End the push block| |@stack('elem')|Show the stack|
@set($variable=[value])
@set($variable)
is equals to @set($variable=$variable+1)
$variable
defines the variable to add. If not value is defined and it adds +1 to a variable.|Tag|Note| |---|---| |@inject('metrics', 'App\Services\MetricsService')|Used for insert a Laravel Service|NOT SUPPORTED|
The next libraries are designed to work with assets (CSS, JavaScript, images and so on). While it's possible to show an asset without a special library but it's a challenge if you want to work with relative path using an MVC route.
For example, let's say the next example: http://localhost/img/resource.jpg
you could use the full path.
<img src='http://localhost/img/resource.jpg' />
However, it will fail if the server changes. So, you could use a relative path.
<img src='img/resource.jpg' />
However, it fails if you are calling the web http://localhost/controller/action/
because the browser will try to find the image at http://localhost/controller/action/img/resource.jpg instead of http://localhost/img/resource.jpg
So, the solution is to set a base URL and to use an absolute or relative path
Absolute using @asset
<img src='@asset("img/resource.jpg")' />
is converted to
<img src='http://localhost/img/resource.jpg' />
Relative using @relative
<img src='@relative("img/resource.jpg")' />
is converted to (it depends on the current url)
<img src='../../img/resource.jpg' />
It is even possible to add an alias to resources. It is useful for switching from local to CDN.
$blade->addAssetDict('js/jquery.min.js','https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js');
so then
@asset('js/jquery.min.js')
returns
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
:file_folder: Example: BladeOne/examples/relative1/relative2/callrelative.php
It returns an absolute path of the resource.
@asset('js/jquery.js')
Note: it requires to set the base address as
$obj=new BladeOne();
$obj->setBaseUrl("https://www.example.com/urlbase/"); // with or without trail slash
Security: Don't use the variables $SERVER['HTTP_HOST'] or $SERVER['SERVER_NAME'] unless the url is protected or the address is sanitized.
It's similar to @asset
. However, it uses a relative path.
@resource('js/jquery.js')
Note: it requires to set the base address as
$obj=new BladeOne();
$obj->setBaseUrl("https://www.example.com/urlbase/"); // with or without trail slash
It sets the base url.
$obj=new BladeOne();
$obj->setBaseUrl("https://www.example.com/urlbase/"); // with or without trail slash
It gets the current base url.
$obj=new BladeOne();
$url=$obj->getBaseUrl();
It adds an alias to an asset. It is used for @asset
and @relative
. If the name exists then $url
is used.
$obj=new BladeOne();
$url=$obj->addAssetDict('css/style.css','http://....');
https://laravel.com/docs/5.6/blade
Instead of use the Laravel functions, for example Form::select
{{Form::select('countryID', $arrayCountries,$countrySelected)}}
We have native tags as @select,@item,@items and @endselect
@select('countryID')
@item('0','--Select a country--',$countrySelected)
@items($arrayCountries,'id','name',$countrySelected)
@endselect()
This new syntax adds an (optionally) non-selected row. Also, BladeOneHTML adds multiple select, fixed values (without array), grouped select and many more.
@section / @show versus @endsection
hello@@world fails to render hello@world. However, hello @@world render hello@world.
extends bug. If you use extends then, every content after the last @endsetion will be rendered at the top of the page.
Solution: avoid to add any content after the last @endsection, including spaces and empty lines.
Some functionalities are not available for PHP lower than 7.0.
bad example:
@extends("_shared.htmltemplate")
@section("content")
@endsection
this is a bug
result:
this is a bug
<!DOCTYPE html>
<html>
<head>....</head>
<body>....</body>
</html>
bad too: (check the empty line at the bottom). This is not as bad but a small annoyance.
@endsection(line carriage)
(empty line)
good:
@endsection
This library is compatible with SourceGuardian.
SourceGuardian provides full PHP 4, PHP 5 and PHP 7 support including the latest PHP 7.2 along with many other protection and encryption features.
However:
BladeOne::MODE_FAST
and encode the compile folder)So,
I don't know about the compatibility of Ioncube or Zend Guard I don't own a license of it.
You are welcome to use it, share it, ask for changes and whatever you want to. Just keeps the copyright notice in the file.
Some features are missing because they are new, or they lack documentation or they are specific to Laravel (then, they are useless without it)
MIT License. BladeOne (c) 2016-2019 Jorge Patricio Castro Castillo Blade (c) 2012 Laravel Team (This code is based and inspired in the work of the team of Laravel, however BladeOne is mostly a original work)