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

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Support

Fetch JSON from external source

Started by Vincent Ramos 8 years ago · 4 replies · 1905 views
8 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
8 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;
        }
8 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 Thomas, 1 week ago
2 56 13 hours ago
Support · by Anna, 3 days ago
2 61 16 hours ago
Support · by Justin Young, 17 hours ago
1 32 17 hours ago
Support · by Duc , 1 week ago
2 66 5 days ago
Support · by Colin Hume, 1 week ago
2 59 5 days ago