飞舞木木

导航

 

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" }}
   because that will echo "whatever" and I don't want that.

I see that I can do

<?php $old_section = "whatever"; ?>
but that's not elegant.

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;/* */ ?>
which sets the variable for us. Without changing any line of code.
posted on 2015-01-19 10:49  飞舞木木  阅读(319)  评论(0编辑  收藏  举报