1

How to extend craft's front end controllers? I don't want to use twig. I like twig but I don't want to use it in craft.

Respect my decision and help me.

Is there a good way to do that?. So I can render using my own views file. So I can use it like in Yii:

public function actionView($id)
{
    $entryData = null; //get the entry data here

    return $this->render('view', [
        'entryData' => $entryData,
    ]);
}
1
  • Respect the decision but can I ask why? Commented May 20, 2022 at 19:14

1 Answer 1

1

Experimented a short while ago on how to do it via a custom module, which I think is cleaner than messing around with craft's own stuff.

(Spoiler: It's faster than twig, but not that much)

You have to do your own routing though.

Example: config/routes.php

'demoview' => 'main/demo/demo-view',
'demoentry/<slug:[^\/].*>' => 'main/demo/demo-entry'

modules/main/controllers/DemoController.php

protected $allowAnonymous = true;

public $layout = 'main';

public function actionDemoView(): string
{
    return $this->render('demoview', [           
        'entries' => Entry::find()
            ->orderBy('title')
            ->all()
    ]);
}

public function actionDemoEntry($slug)
{
    $entry = Entry::find()->slug($slug)->one();
    if (!$entry) {
        throw new NotFoundHttpException();
    }

    return $this->render('demoentry', [
            'entry' => $entry
        ]
    );
}

Views:

modules/main/views/demo/demoview.php modules/main/views/demo/demoentry.php modules/main/views/layouts/main.php

Use a behavior instead of $entry->url, e.g.

public function getDemoUrl()
{
    return UrlHelper::siteUrl("/demoentry/{$this->owner->slug}");
}
3
  • Thank for your response but nothing has changed. I'm new to craft.
    – user
    Commented May 21, 2022 at 12:25
  • what class should DemoController extend?
    – user
    Commented May 22, 2022 at 0:44
  • 1
    Besides handling content via craft\elements\Entry there is nothing Craft specific here, all pure Yii2 (see routing/views/behaviors there). The controller extends either yii\web\Controller or craft\web\Controller (better control who can access the actions)
    – user8315
    Commented May 23, 2022 at 6:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.