K2 Return a snippet as parsed text from route

Is it possible to return a snippet as parsed text from a route?

Something like:

config.php

c::set('routes', array(
  array(
    'pattern' => 'eco',
    'method' => 'post',
    'action'  => function() {
      try {
        return response::json(json_encode(snippet('anything', [], true)));
      } catch (Exception $ex) {
        return $ex->getMessage();
      }
    }
  )
));

then in JS, something like:

var url = baseurl + '/eco';
fetch(url, {
  method: 'post',
  body: JSON.stringify({blah: 'bleh'}) ,
  headers: {'Content-type': 'application/json '}
  }).then(function (response) {
    return response.json();
  }).then(function (data) {
    console.log(data);
  })

This can be done in K3 without response::json as in:

...
return json_encode(snippet('anything'), [], true)
...

…but in K2 I am getting an exception:

Argument 1 passed to Kirby::render() must be an instance of Page, boolean given, called in /home/jaume/public_html/dev/langkit-master/kirby/kirby/component/response.php on line 25

Thanks

I would suggest upgrading. Kirby 2 is end of life tomorrow.

Thanks @jimbobrjames but they won’t pay for it (the license or my time for the upgrade), and still want certain changes done.

That code should actually work, unless you use variables in it that are not defined inside the snippet. So you would have to pass them to your snippet instead of the empty array in your route.

1 Like