首页 > 其他 > 详细

how to add variable in blade template?

时间:2015-01-19 12:16:14      阅读:299      评论:0      收藏:0      [点我收藏+]

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.

how to add variable in blade template?

原文:http://www.cnblogs.com/mumutouv/p/4233193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!