Laravel 4 blade syntax within my javascript files

妖精的绣舞 提交于 2019-11-30 23:21:47

问题


My home page had some inline javascript that was mixed up with some blade syntax e.g.

    <script type="text/javascript">
        @if(Auth::user())
            if(path.indexOf('/user/' + {{Auth::user()->id}} ) != -1) {
                    $( "#tabs" ).tabs();
            };
        @endif
    </script>

It worked until I wanted to move the javascript to an external file.js. I got error whenever blade syntax was added. Is there a way I can fuse blade syntax in my javascript files.js? I tried renaming to file.blade.js with no luck...


回答1:


you can try this save your javascript file in app/views folder and rename it to xxx.blade.php , yes .blade.php because Blade Engine will parse it only if its .blade.php and use @include('your javascript filename') to include the javascript file parsed by Blade, it will work.




回答2:


Although the accepted solution will work, this is a most definitely an antipattern.

If I saw this not being the one who wrote it, I would be extremely confused to what's going on.

My suggestion is in your PHP file, have a block, which gets all of the values that you'll need in your external files, then call the external files.

So in your PHP file you would have something like:

<script>
    var userID = "{{ Auth::user()->id }}";
    var isUser = "{{ Auth::user() }}"
</script>

{{ HTML::script('path/to/js/file.js') }}

And in your javascript file:

if(isUser)
{
    if(path.indexOf('/user/' + userID ) != -1) {
        $( "#tabs" ).tabs();
    };
}



回答3:


I was doing the same than @BrandonRomano, but I found a better approach. Sending directly the value from PHP to JS vars using: PHP-Vars-To-Js-Transformer

PHP:

JavaScript::put([
    'foo' => 'bar',
    'user' => User::first(),
    'age' => 29
]);

JS:

console.log(foo); // bar
console.log(user); // User Obj
console.log(age); // 29

You can set a namespace like:

console.log(server.foo)



回答4:


You are outputing string from PHP, so you have to enclose that string in '

<script type="text/javascript">
    @if(Auth::user())
        if(path.indexOf('/user/' + '{{Auth::user()->id}}' ) != -1) {
                $( "#tabs" ).tabs();
        };
    @endif
</script>


来源:https://stackoverflow.com/questions/18074771/laravel-4-blade-syntax-within-my-javascript-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!