Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 blade syntax within my javascript files

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...

like image 646
Tim Truston Avatar asked Aug 06 '13 08:08

Tim Truston


1 Answers

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();
    };
}
like image 155
Brandon Romano Avatar answered Oct 30 '22 02:10

Brandon Romano