2

Hi Not sure on the best way to do this. I have some javascript that requires a json formatted file to populate a calendar. I can do this in php by adding the following to the file that is being requested:

header('Access-Control-Allow-Origin: *');
    $array = array(
    array('date' => "27/9/2015", 'title' => 'BBC Event', 'link' => 'http://www.bbc.co.uk')
    );
echo json_encode($array);

I need to be able to do the same with craft. I have tried just formatting the entries in twig which returns the json as it should be but because the header is missing the javascript call does not run it. I have also created a small plugin to pull out all the entries which may be a better option. I just need to know how to return those entries in json to a template as per the above php would create with a header included.

Any help much appreciated.

Cheers

4

You can set the header in Twig with the {% header %} function. Like this:

{% header "Content-Type: application/json; charset=utf-8" %}
{% header "Access-Control-Allow-Origin: *" %}

As to generating the actual json, my favourite is using the prune plugin and do it like this:

{% set myEntries = craft.entries.section('mySection').find() %}

{
    {%- spaceless -%}
    "myEntries": {{ myEntries | prune(['onefield', 'anotherfield']) | json_encode() | raw }},
    {%- endspaceless -%}
}

You could also just loop over all the entries and create the json yourself, but I always get into all sorts of issues with encoding when doing that.

If you're going to do a lot of json requests, you could also look into the Element API plugin from Pixel & Tonic. You'd probably have to set the headers on the webserver level (.htaccess or nginx.conf) though.

| improve this answer | |
  • Awesome this worked a treat. Cheers @andre – Lettie Oct 3 '15 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.