首页 > 代码库 > how to add variable in blade template?
how to add variable in blade template?
question?
I‘m reading Laravel Blade‘s templating docs and I can‘t find how I can assign variables inside a template for use later in the template. I can‘t do
{{ $old_section = "whatever" }}
I see that I can do
<?php $old_section = "whatever"; ?>
answer
You can put it in your application/start.php or if you will have more things like this put it in a separate file and include it there. Laravel is very loose in this way, you could even put thin a controller. The only thing you have to do these extends before the view is rendered.
<?php/** * <code> * {? $old_section = "whatever" ?} * </code> */Blade::extend(function($value) { return preg_replace(‘/\{\?(.+)\?\}/‘, ‘<?php ${1} ?>‘, $value);});
answer
In laravel-4, you can use the template comment syntax to define/set variables.
Comment syntax is {{-- anything here is comment --}}
and it is rendered by blade engine as
<?php /* anything here is comment */ ?>
so with little trick we can use it to define variables, for example
{{-- */$i=0;/* --}}
will be rendered by bladeas
<?php /* */$i=0;/* */ ?>
how to add variable in blade template?