Question

I hope to define global variable in a separate file and then inject in wherever I want, so for Laravel 4 + Blade, I did this.

Top file example.blade.php:

@include('head')    
@include('body')

head.blade.php

$STYLE_PATH_CSS="styleFolder/foundation/css" 
$STYLE_PATH_JS="styleFolder/foundation/js" 
$STYLE_PATH_JS_VENDOR="styleFolder/foundation/js/vendor"
<link rel="stylesheet" href=" <?php echo $STYLE_PATH_CSS ?>/normalize.css ">
<link rel="stylesheet" href=" <?php echo $STYLE_PATH_CSS ?>/foundation.css ">
<link rel="stylesheet" href=" <?php echo $STYLE_PATH_JS_VENDOR ?>/modernizr.js "> 

body.blade.php

<script src="styleFolder/foundation/js/vendor/jquery.js"></script>
<script src="styleFolder/foundation/js/foundation.min.js"></script>

Until then, it works fine. Then I hope to simplify one more time: replace the duplicate path by global variable. So,

variables_G.blade.php

<?php  $STYLE_PATH_CSS="styleFolder/foundation/css" ?>
<?php  $STYLE_PATH_JS="styleFolder/foundation/js" ?>
<?php  $STYLE_PATH_JS_VENDOR="styleFolder/foundation/js/vendor" ?>

and new head.blade.php

@include('variables_G.blade.php')
<link rel="stylesheet" href=" <?php echo $STYLE_PATH_CSS ?>/normalize.css ">
<link rel="stylesheet" href=" <?php echo $STYLE_PATH_CSS ?>/foundation.css ">
<link rel="stylesheet" href=" <?php echo $STYLE_PATH_JS_VENDOR ?>/modernizr.js "> 

then it can't find variables' value. Error message:

Undefined variable: STYLE_PATH_CSS.

Can anyone help me out?

Was it helpful?

Solution 2

Views are supposed to be dumb, this means also that you should not create variables inside of one to give to another, you should not give too much resposibility to a view.

The best way to provide global variables to Blade Views and make sure they will be available at any time is using View::share():

View::share('STYLE_PATH_CSS', 'styleFolder/foundation/css');
View::share('STYLE_PATH_JS', 'styleFolder/foundation/js');
View::share('STYLE_PATH_JS_VENDOR', 'styleFolder/foundation/js/vendor');

You can add this to a composers.php file and load it in your app/start/global.php:

require app_path().'/composers.php';

Take a look at the docs: http://laravel.com/docs/responses#views

OTHER TIPS

View::share(); is the best way to make a global variable.

View::share('name', 'Steve');

To make sure a certain variable is included every time a certain view is rendered, I like View Composers

You can include stuff when certain views are rendered. I suppose you could use it on your master layout(s), to make things almost global. It gives more control, which would be good if you need something widely available, but if it is sensitive and you don't want it everywhere.

View::composer('profile', function($view)
{
    $view->with('count', User::count());
});

View::share('name', 'value'); easiest way to define global variable

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top