Using twig functions (pyro module plugins) and models
Created 7 years ago by keevitaja

Hello!

I have a controller, that returns a view response. Into the view i inject eloquent model:

<?php

namespace Acty\ClassifiedsModule\Http\Controller;

use Acty\ClassifiedsModule\Advert\AdvertModel;
use Acty\ClassifiedsModule\Advert\AdvertRepository;
use Anomaly\Streams\Platform\Http\Controller\PublicController;

class AdvertsController extends PublicController
{
    public function show(AdvertModel $advert, $id)
    {
        return classifieds_views('classifieds.adverts.show', [
            'adverts' => $advert
        ]);
    }
}

And in the view template i can do stuff like that:

{% for advert in adverts.get() %}
    {{ advert.name }} <br>

    {% for image in advert.gallery %}
        {{ image.image.url }}
    {% endfor %}
{% endfor %}

gallery is a files relation.

But when i try to do same thing with a twig function:

    public function __construct(AdvertModel $advert)
    {
        $this->advert = $advert;
    }

    public function getFunctions()
    {
        return [
            new Twig_SimpleFunction('adverts', function() {
                return $this->advert;
            }),

I get this error:

An exception has been thrown during the rendering of a template 
("Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation") 
in "/home/user/www/horses/addons/horses/acty/horses-theme/resources/views/classifieds/adverts/show.twig" at line 5.

But the model is there. I can do {{ image }} instead of {{ {{ image.image.url }} }}

Any help with this one?

I would need to use this function inside themes template files too

ryanthompson  —  7 years ago

You can't use it like you would a presenter cause it's not being defeated so try using literal methods.

keevitaja  —  7 years ago

@ryanthompson how can i use it? I need this in theme templates too.

ryanthompson  —  7 years ago

Something like {% for image in adverts.gallery().get() %} should do the trick.