4

Let's say I have a piece of jQuery javascript that binds to a div on load and dynamically defines an img in that div. Something like this:

$(document).ready(function() {
    $("#container").html("<img href='/images/myimage.jpg/>');
});

If I were to use this inlined in a Laravel view, I'd be able to use HTML::image() and Blade templates to specify the location of image. Something like this:

$(document).ready(function() {
    $("#container").html("{{ HTML::image('images/myimage.jpg', 'My image') }}");
});

If I were then to take that piece of javascript, and, instead of inlining it in the view, place it inside a separate .js file, say, public/js/image.js, I could have Laravel load it as an asset;

Asset::add('image.js', 'js/image.js');

However, since it's now treated only as an asset, neither the Laravel PHP nor the Blade templating code is processed, so we literally get the string {{ HTML::image('images/myimage.jpg', 'My image') }} in the resulting html, instead of the templated-in values.

Is there a good approach for something like this?

4
  • Not without sending it to the server so you could run it through the Blade parser and get the parsed string back. Or you could just use raw HTML, as you showed in your first code example. Commented May 19, 2013 at 17:51
  • Are you only asking this to get the base URL appended? Commented May 19, 2013 at 18:33
  • I just chose the specifics for the example. A general accepted technique would be useful. Commented May 19, 2013 at 18:58
  • 1
    Generally - don't mix php and JS. If you need to pass values to a JS script either output it as a meta/link tag in your HTML, or write some javascript out to the page that does such config - like google analytics might. Commented May 19, 2013 at 19:32

2 Answers 2

4

I'm doing this here. The way I found was:

1 - create a 'js' file inside the view directory tree, something like

app\views\javascript\mycustomJS.blade.php

2 - then render it wherever you need:

<script>
    @include('javascript.mycustomJS')
</script>

It's blade, it will be processed as it should.

This is far from ideal, I know, but it works for me, for now. :)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm using you solution right now. Did you find any better way of solving this problem? btw Thank your for the solution
0

I think you can put it in a php file. I've done this before with css.

Asset::add('image.php', 'js/image.php');

1 Comment

No. This doesn't work. CSS may be included with this technique, but a PHP file is still not parsed as a PHP file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.