2

Is there any way to include the JSON response from element API in a template. Let's take the following example:

/case-studies.json returns:

{
    data: [
        {
            title: "American Express",
            color: "#0000ff",
            url: "http://localhost:3340/index.php?p=case-studies/american-express"
        },
        {
            title: "Bosch",
            color: "#ffffff",
            url: "http://localhost:3340/index.php?p=case-studies/bosch"
        }
    ]
}

I want to known if I can include this JSON object into my template case-studies/index.html, so it looks like:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <...>            

        <script>
            window.data = [
                {
                    title: "American Express",
                    color: "#0000ff",
                    url: "http://localhost:3340/index.php?p=case-studies/american-express"
                }, {...}
            ];
        </script>
    </body>
</html>

I just wanna avoid the first ajax call when I load the page for the first time by including the data in the HTML body. Further on, I will use Ajax calls instead.

2

I can't think of a clean way to do this.

The Element API plugin currently will set JSON headers on the response and return the data JSON encoded, so it's not easy to directly embed in a template.

A few options I can think of would be to fork the plugin and add the ability to return JSON in the format a template can directly utilize. Or you could have a wrapper plugin that made an AJAX call to the Element API endpoint, grabbed the response and massaged the data into a format your template could directly utilize.

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.