Loilo Loilo - 4 months ago 36
Ajax Question

How to share templates between Laravel and JavaScript?

I have just started working with Laravel and I'm pretty excited about the possibilites it provides. (I never used a PHP framework, to be honest.)
But there's still a fundamental problem I have when developing a web application:

How do I share template information between my PHP backend and JavaScript / AJAX requests?

Times ago I just sent my AJAX requests and had the HTML generated by the server and sent as such. Today I my AJAX data as JSON but I have no idea how to use the same template (e.g. a users list) at the server side and (for refreshing, filtering etc.) at client side without creating redundant layout code.

So long story short: Is there a template language with parsers as well for PHP/Laravel and JavaScript?

The Lavarel template engine Blade is obviously not usable in JavaScript.
The only sharing template language I found via Google was Mustache, but the parser for Lavarel was outdated.

Is there anything else out there and which approach do you use for that - I'm surely not the only one with this problem.


Your boiled down question:

Is there a template language with parsers as well for PHP/Laravel and JavaScript?

Laravel and Mustache | server side:

  • conarwelsh/mustache-l4 is a Mustache.php wrapper for Laravel 4. They seems to keep up very well as opposed to what you tell (I presume you mean michaelenger/mustacheview which is actually a Laravel 3 bundle). I stand corrected if am wrong.

  • Laravel's Blade doesn't rule out Mustache at all. You just have to create a Mustache partial without using blade.php extension and include it within a regular Blade template using @include (More details here)

Serving Mustache template:

  • You can even coin any custom Response you need using Response Macros such Response::mustache(...) leveraging Response::make(...) (see here for more details).

Some samples of interest:

My short answer (Updated):

Don't look elsewhere: Laravel + Mustache + Javascript if a mix of server|client side rendering is part of your requirements.

Get your hands dirty! :)