1

What I want to do:

I have an application based on symfony2 (php). A simple action returns data as json like this

    $headers = array(
        'Content-Type' => 'application/json'
    );

    return new Response($data, 200, $headers);

This action is called from javascript like this

function loadData(action){
    $.ajax({
        type: "POST",
        url: action,
        success: function(data){
            console.log(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

So this seems very basic so far. From the console I can see the correct data returned. This data should be placed somewhere on the project website.

Question:

Is there any straight forward way to create html from json within javascript? Actually I want seperate templates (twig) from the logic of the project. So would it be correct to generate the html e.g. in the success callback in the loadData method?

I could bypass this problem by returning html instead of json. But I think about building some kind of rest api for my project which I think required json for transport.

Any suggestions or ideas? Please share your ways of handling this.

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
  • Of course but where is your json. i mean a sample of your json response – Jai Apr 02 '13 at 08:29
  • 2
    Just a note but for a JSON response you can use `Symfony\Component\HttpFoundation\JsonResponse->create()` without the need to send your own headers or status stuff. – qooplmao Apr 02 '13 at 08:59
  • "I could bypass this problem by returning html instead of json. But I think about building some kind of rest api for my project which I think required json for transport." could you explain more about this? – ianace Apr 02 '13 at 09:29
  • You could do like Facebook does and return a pre generated HTML using `$view = $this->renderView('Blah:Blah:some_content.html.twig, $vars)` then `return new JsonResponse(array('view' => $view))` and finally using jQuery to fill the space needed using `return (data) {$('#blah').html(data.view);}` but then it's not overly portable. – qooplmao Apr 02 '13 at 09:32
  • @Jai json response is a serialized set of objects – DarkLeafyGreen Apr 02 '13 at 09:57
  • @ianace I mean it juts like Qoop explains it in his comment, just without the json part – DarkLeafyGreen Apr 02 '13 at 09:57
  • @Qoop sounds like a good way to do this – DarkLeafyGreen Apr 02 '13 at 10:19
  • @artworkadシ i mean what's preventing you from doing something like this.. put all html inside an array and json encode that array? for example $array_to_be_json = array('header'=> /*html placed inside a php variable here*/ ,'footer'=> /*another html placed inside php variable*/); echo json_encode($array_to_be_json) ... then let javascript parse that object append accordingly to what the index is.. am i making sense? – ianace Apr 02 '13 at 13:57

3 Answers3

2

You can use angular js. It have one good thing for symfony:

angular.module('myApp', []).config(function($interpolateProvider){
        $interpolateProvider.startSymbol('[[').endSymbol(']]');
    };
);

It changes {{ with [[ and let you use template in TWIG.

This will help with json query in angular js.

Community
  • 1
  • 1
Narek
  • 3,813
  • 4
  • 42
  • 58
1

Get the data and send it back to the server ? I think its not correct.

Try to look at underscore.js ( _.template() ) for templating on client side with received json object.

And try to use TWIG like this:

_.templateSettings = {
  interpolate : /\[\[(.+?)\]\]/g
};

var template = _.template("Hello [[ name ]]!");
template({name : "Mustache"});
=> "Hello Mustache!"
Kirill
  • 19
  • 5
0

Take a look at Handlebars.

You can basically pass the JSON to a Handlebars template:

The template:

<script id="entry-template" type="text/x-handlebars-template">
    <div class="entry">
        <h1>{{title}}</h1>
        <div class="body">
            {{body}}
        </div>
    </div>
</script>

The JS:

var source   = $("#entry-template").html(),
    template = Handlebars.compile(source),
    context = {title: "My New Post", body: "This is my first post!"},
    html    = template(context);

The result:

<div class="entry">
    <h1>My New Post</h1>
    <div class="body">
        This is my first post!
    </div>
</div>
Jonas G. Drange
  • 8,749
  • 2
  • 27
  • 38