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.

8
  • Of course but where is your json. i mean a sample of your json response Commented Apr 2, 2013 at 8: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. Commented Apr 2, 2013 at 8: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? Commented Apr 2, 2013 at 9: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. Commented Apr 2, 2013 at 9:32
  • @Jai json response is a serialized set of objects Commented Apr 2, 2013 at 9:57

3 Answers 3

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.

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

1 Comment

Great thing. Gonna give it a try
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!"

Comments

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>

3 Comments

In twig used same syntax {{ so there will be problem with using it in templates. Is there any method to change {{ with [[ for example?
In this case you will not be able to use for example system vars in twig.
You can end the verbatim tag at any time.

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.