Skip to content
Grav 2.0 is officially stable. Read the announcement →
Support

Fetch JSON from external source

Started by Vincent Ramos 9 years ago · 4 replies · 2082 views
9 years ago

Hello, loving grav so far but had a question regarding fetching JSON from an external source. I want to hit an endpoint and set the JSON object to a theme variable and render it that way. I am currently doing it with javascript but would rather use twig.

Is there a plugin or code snippet that would help me achieve this?

👍 1
9 years ago

Thanks for pointing me in the right direction, I managed to get the JSON via cURL but am having a hard time exposing the data to the template via twig. Is there a way to return a twig variable here:

PHP
        public function getFunctions()
        {
            return [
                new \Twig_SimpleFunction('jobs', [$this, 'getJobs'])
            ];
        }
        public function getJobs()
        {
            $url = "https://api.greenhouse.io/v1/boards/companyId/jobs";

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_URL,$url);
            $result=curl_exec($ch);
            curl_close($ch);

            // Assign Twig Var here?
            return $result;
        }
9 years ago

You can't return a variable, twig function just return a string or an object. The $results you are already returning should work:

TWIG
{% set jobs = jobs() %}
{{ dump(jobs) }}

Should show you the result you want as the variable result. Turn on the debugger and look in the Messages panel to see the output of that dump.

Suggested topics

Topic Participants Replies Views Activity
Support · by Paul Hodges, 4 weeks ago
19 485 5 days ago
Support · by Lauw, 7 days ago
2 99 7 days ago
Support · by Anna, 3 weeks ago
4 426 1 week ago
Support · by gtx, 4 weeks ago
4 377 3 weeks ago
Support · by Anna, 1 month ago
9 484 3 weeks ago