beebmx / kirby-blade

Enable Blade for Kirby 3 & 4
MIT License
15 stars 3 forks source link

Generating JSON representation #5

Closed marcschneider123 closed 2 years ago

marcschneider123 commented 4 years ago

I am trying to generate a JSON representation of my blog articles like so https://getkirby.com/docs/cookbook/templating/generating-json

/site/templates/blog.json.php

<?php

$data = $pages->find('blog')->children()->published()->flip();
$json = [];

foreach($data as $article) {

  $json[] = [
    'url'   => (string)$article->url(),
    'title' => (string)$article->title(),
    'text'  => (string)$article->text(),
    'date'  => (string)$article->date()
  ];

}

echo json_encode($json);

Accessing the url "/blog.json" i don´t get the JSON data, just my default.blade.php template with content-type set to 'application/json'.

How can i retrieve the JSON data of my blog articles?

PaulMorel commented 3 years ago

I'm having the same problem and currently troubleshooting it. It seems like if the the normal HTML Blade Template exists, the other representations are ignored. I'll come back with a potential fix if I find one.

PaulMorel commented 3 years ago

I was able to get content representations to work by editing a couple of functions in the /src/Template.php file of the plugin.

    public function getFilename()
    {
        if ($this->isBlade()) {
            return $this->root() . '/' . $this->name() . ( $this->hasDefaultType() ? '.' : ".{$this->type()}." ) . $this->bladeExtension();
        } else {
            return $this->root() . '/' . $this->name() . ( $this->hasDefaultType() ? '.' : ".{$this->type()}." ) . $this->extension();
        }
    }

    public function isBlade()
    {
        return !!file_exists($this->template . '/' . $this->name() . ( $this->hasDefaultType() ? '.' : ".{$this->type()}." ) . $this->bladeExtension());
    }

@beebmx I've quickly tested this and it seems like it works. Would you like me to submit a PR?

beebmx commented 3 years ago

Sure