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 have 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.
Is there a template language with parsers as well for PHP/Laravel and JavaScript?
The Laravel template engine Blade is obviously not usable in JavaScript.
The only sharing template language I found via Google was Mustache, but the parser for Laravel was outdated.
Is there anything else out there and which approach do you use for that?
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:
Combining Laravel 4 and Backbone.
Sharing Templates Between PHP and JavaScript | PHP but still relevant!
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! :)
I had the same issue with Laravel and Angularjs, what I did is that I created a route to return templates http://domain.com/templates/name
This route will View::make('templates'.$name);, this is an AngularJs template that will be filled with data returned by JSON API. Remember to use non conflicting tags I used {{ for Laravel and <% for Angular.
RENDER YOUR TEMPLATE SERVER SIDE! I'm not sure at what point someone decided you needed to send JSON to the front end, but that's not how they do it in Rails. In Rails, they actually render the template server side, then send it back to the front end and your JS appends it to the page (or, actually sends back the JS + the markup to attach). This saves a ton of time and headache, trust me.
Related
When it comes to Ajax, it looks like Symfony (v. 2.7) and AngularJS (v. 1.4) don't go well together ;-)
I see two ways to make them cooperate - my question is: Which one is better?
Adapt AngularJS to be compatible with Symfony
Adapt Symfony to be compatible with AngularJS
For 1, this is the best instruction I found:
http://harmssite.com/2014/09/mixing-angular-and-symfony/
Advantage: Can use $form->handleRequest($request); in Symfony to get all form fields at once.
Disadvantage: Cannot set default value's for <input>'s, cause AngularJS overwrites them. Solution:
Set it in Angular's controller (i.e. in app.js). But if the value comes from the database (i.e. Symfony), how can you get it into app.js? Render the entire app.js file through Symfony's templating system? => Looks like overkill to me.
Set it inside the HTML/twig file with ng-init, as shown here:
AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?
=> This is more a workaround than a solution ;-)
For 2, the major disadvantage is that you need to read each form field separately into Symfony, using $post = $this->getRequest()->getContent(); as shown here:
AngularsJS POST JSON data to Symfony2
I haven't tried this approach, so I don't know if there are further problems down the way ;-)
After fiddling around with this for a while, I finally came to a solution: Kick out AngularJS completely!
As far as I understand it now, AngularJS is only the way to go, if you are processing your forms completely (or at least mainly) on the client-side. I guess, that's what they mean by "Single Page Application (SPA)".
If you're using Symfony for form processing, AngularJS probably makes your life harder, not easier.
I'm now using plain jQuery for JavaScript, and everything works like a charm (including Ajax), much more hassle-free than AngularJS was.
If you just need to handle AJAX Requests from AngularJS to Symfony2 server, using classic forms (without Symfony2 form builder), you can use this bundle :
qandidate/symfony-json-request-transformer
Add it as a dependency in your composer.json and handle your requests (POST & other methods) in the same way as classic request.
You can See my post about this problem : Handling HTTP Requests from AngularJS to Symfony2
Other tip, to use AngularJS in your twig templates, add this in your angular app :
var app = angular.module('yourApp', [],
function($interpolateProvider){
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
This will change your start symbol from {{ to <% and your end symbol from }} to %>
In my case, use AngularJS make my work easier and me more productive, especially coupled to a Symfony back-end, but it's very personal, and depending on why/how angular is used.
My understanding (or misunderstanding): I've just started learning the mean stack and i see that a lot of tutorials (most are pretty old) and some template projects (like mean.io) using angular for routing instead of express (about 80% angular routing and 20% express). My understanding of angular routing is that it is suppose to ajax in a template into the ngView which would keep the page from reloading giving me a true single page application.
my setup: So i have express routing all request to the index file and from there i have created routes in angular for all possible request. each request is routed by angular to a jade template file (which i've seen called partials).
The issue: so i thought that angular would be ajaxing in the partial with each request (giving me the benefit of not having the whole page reload) making a true single page application, but what i've found is that because express (or any other web server for that matter) is routing all request to the index file so angular can do it's thing the index file is always reloaded with each request. because of this, I feel like the ajax routing is meaningless. After all, if the index file is always reloaded on each request which in turn reloads the angular files (and all the js and css files called in the head) then there is no real difference between angular routing and express routing coupled with jade template includes.
The question: Is this the way angular routing coupled with express is meant to be set up and suppose to function or am i doing it all wrong (or when using the mean stack, is it more of a personal choice as to which routing to use rather than a distinct advantage/dis-advantage)?
I see what is going on here: the ajax only seems to happen when following a link from within the browser. If you manually modify the url in the browser bar to test the link it will reload everything. Now i feel silly as hell.
I was at an interview yesterday and the interviewer asked me a few questions about blade and I replied saying that I don't use blade and only use Laravel to build RESTful web services which I then consume using a front end technology such as Angular.
He insisted that blade was very useful and there a few disadvantages to not using blade. I couldn't understand what he was talking about. And neither do I clearly remember any points he made.
I am curious to know are there any disadvantages to not using blade in Laravel?
In my opinion there are a few advantages of AngularJS over blade and vice versa:
Advantages blade:
Laravel has some html helpers and form helpers.
Laravel adds a token to a form for preventing csrf!
When you open a form you can give a route to it. The method and the action are defined by blade based on the given route.
With blade you can create macro's and view composers.
When validating a form you can return back with the input and the errors which is quite easy.
Blade is not realy slow because laravel cache the compiled views.
With blade you can extend and include views which is more DRY(Don't Repeat Yourself)
On paginator objects you can call ->links() which is very easy for pagination although this is also nice to do with AngularJS.
Blade can automatically escape you're data with {{{$var}}}.
If you've to write a multi language application blade and laravel comes with easy methods to do achieve this.
This are in my opinion the advantages of blade. Look at the blade docs for more information and figure out what you like!
In the views in codeigniter, we can write code for forms using codeigniter. For example for an url the code in codeigniter is:
<?php
anchor('site/myfunction','Send');
?>
My question is whether is better write this code with html in the views:
Send
It's an example, but the question is with all HTML helpers for views. CodeIgniter's user guide suggests to use PHP functions rather than code html. The php code requests to the server while html does not. Is better use the CodeIgniter for HTML? I don't know if when I use CodeIgniter's helpers, the framework has contemplated these requests.
I apologize for my english. Thanks for your answer.
The reason you want to use CodeIgniters library is for the ability to quickly modify your HTML elements site-wide with very little work. For instance, let's say you wanted all <a> tags on your site to have a class added called "ajax". Using the anchor helper, you can accomplish this easily.
That said, I don't really foresee many solutions where you will be changing HTML elements site-wide. With semantic HTML, CSS, and Javascript I think you will be perfectly fine without having to use CodeIgniters HTML helpers. Also in my opinion your code will be much more readable. Use HTML.
Regarding performance
When you say "code php does requests to the server while html, no" you're wrong because whenever someone visits your site they are requesting the server. The question here is how much work the PHP engine is doing versus just your normal webserver. In this case, a function call is trivial for PHP and shouldn't be considered performance wise.
Regarding urls
The answer by Pi is focused on the fact that URL resolution in CodeIgniter can be weird, but with proper .htaccess or web.config configurations you should be able to use vanilla hrefs without using CodeIgniter functions.
You should not use
Send
Because it might not work everywhere. But if you use this:
Send
There will be no big difference. Pure HTML is a bit faster but unless you have a high traffic website that does not matter. Using the CI function is nice if you are in a library because you do not want to mix PHP and HTML to much to keep up the Model-View-Controller concept. What you use in a view is a matter of style what you like more.
Personally I think the codeigniter form functions are not very good and I am often use html instead.
I'm working on a website that uses AJAX to retrieve data from the server and display it on the page. Django renders the initial page content using its template engine (so it will be indexed by search engines). When the user takes an action, jQuery fetches the new data via AJAX and the response is returned as JSON. I would like to have jQuery render this new content without violating the DRY Principle. Therefore I would like to use a templating engine that is "shared" between Django and jQuery. I've been running in circles trying to find the best solution but always seem to run into a road block.
Has this already been done? Here are the options I have thought of:
Use regular expressions to transform the Django template into correct jQuery template syntax, and render it in its raw form to the page. jQuery will then pick it up and use it to render the new data.
Extend the jQuery template engine to recognize the Django template syntax, again rendering the raw Django template to the page for jQuery to use.
Has this been successfully done before? Either way seems like a lot of work for anything but the simplest of Django templates because of the plethora of Django tags and filters that would need accounted for.
Your best bet is to pick a template language that has both Javascript and Python support, and use that everywhere.
As far as I know, Mustache is your best bet.
I haven't found a perfect solution since I asked this question, but for the sake of development time I resorted to sending back both JSON and HTML in the AJAX response. This way the django templates still perform the HTML generation, but javascript is still free to utilize the data without having to parse the HTML.
I am sending approximately twice the data over the network, but I'm going to live with it until my application grows to the point where a smaller response is beneficial. At that point I will probably look into something like Mustache as Rob mentioned.