Laravel 5 Implementing Template Theme Features
Many CMS have template theme function, we can change the theme through a configuration, this function in Laravel how to implement it? Today we are going to discuss this problem.
As we all know, the Laravel rendering template is implemented through View::make (), and you need to explicitly specify the template file path:
The code is as follows:
Function index ()
{
Return View::make (' Index.index ');
}
In this case, we can implement the template theme function, we just need to put the template file in a topic name corresponding to the directory, such as the default theme is the defaults, we wrote:
The code is as follows:
Function index ()
{
Return View::make (' Default.index.index ');
}
Customizing the theme Custom:
The code is as follows:
Function index ()
{
Return View::make (' Custom.index.index ');
}
To read the subject name from the configuration file:
The code is as follows:
Function index ()
{
Return View::make (Config::get (' app.theme ', ' Default '). Index.index ');
}
This basically implements the theme of the template function, but there is a problem, that is, the custom theme must implement all the default theme of all templates, otherwise it will cause some page template file does not exist error, then further optimization:
The code is as follows:
Function index ()
{
$theme = Config::get (' app.theme ', ' Default ');
$TPL = $theme. '. Index.index ';
if (! View::exists ($TPL)) {
$TPL = ' Default.index.index ';
}
Return View::make ($TPL);
}
is to detect if the template file exists before rendering the template, and use the corresponding template in the default theme if it does not exist.
So many lines of code, we can continue to encapsulate, this time to use the Response object, we know that Response::view () is equivalent to View::make (), and Response has a method Response::macro () Method can be used to define a macro, we can encapsulate the logic into the macro:
The code is as follows:
Response::macro (' Render ', function ($path, $data =array ()) {
$theme = Config::get (' app.theme ', ' Default ');
$TPL = $theme. '. '. $path;
if (! View::exists ($TPL)) {
$TPL = ' Default '. $path;
}
Return Response::view ($TPL, $data);
});
Use:
The code is as follows:
Function index ()
{
$bindings = Array (
' title ' = ' Home '
);
Return Response::render (' Index.index ', $bindings);
}
It is important to note that the variables passed into the template pass the second parameter of Response::render.
Today's tutorial first come here, follow-up we have to further analysis, I hope you can enjoy.
http://www.bkjia.com/PHPjc/962929.html www.bkjia.com true http://www.bkjia.com/PHPjc/962929.html techarticle laravel 5 Implement template theme features many CMS have template theme function, we can switch the theme through a configuration, this function in Laravel how to implement it? Today we are going to explore ...