Skip to content
Grav 2.1 is out: every page speaks Markdown. Read the announcement →

Fetch JSON from external source

Started by Vincent Ramos 9 years ago · 4 replies · 2147 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 blu3prince, 4 days ago
1 65 3 hours ago
Support · by complanar, 7 days ago
6 156 1 day ago
Support · by Rick Beebe, 7 days ago
2 115 3 days ago
Support · by alex, 5 days ago
2 101 4 days ago
Support · by Marcel, 2 weeks ago
1 151 4 days ago