Fetch JSON from external source

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 Like

This is really beyond the default capability of Twig which is a templating language. If you really MUST do it from Twig, you could create a plugin that uses a custom function. There are examples of this being done in plugins such as Star Ratings

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:

        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);
            // Assign Twig Var here?
            return $result;

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

{% 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.

This did the trick! Thank you! :pray: