2

The only thing I don't really like about Craft is that I have to fetch and eventually manipulate my entry in the twig template itself.

Is there a way to hook into the current request before the template gets rendered? Like that I could create some kind of Controller where I fetch all the necessary data, prepare it and then pass it on to the template.

Additionally this would allow me to use another template engine then twig.

If this is not possible, would there be a way to only use craft as the backend? From outside of craft, is there an easy way to find out if there are matching entries/singles/categories to the current request? I'm not looking for a complete answer here, more some key points where I could start looking.

0

Is there a way to hook into the current request before the template gets rendered?

Sure, Craft does this in several places in the Control Panel itself.

A plugin can registerCpRoutes hook. From there, you'd define an action route like so:

return array(
    'cocktails/(?P<widgetId>\d+)' => array('action' => 'cocktails/editCocktail'),
);

That will send the request to your plugin's CocktailsController's actionEditCocktail. There you can prep any data that you want and pass it off to a template to render:

$variables['name'] = 'Martini';
$variables['ingredients'] = array('Gin', 'Olives');

$this->renderTemplate('cocktails/_edit', $variables);

And access those from the template via {{ entry.name }} or:

{% for ingredient in entry.ingredients %}
    {{ ingredient }}
{% endfor %}

Additionally this would allow me to use another template engine then twig.

I'm not seeing how you'd easily be able to do this, though.

Update:

There is also the Template Hooks, which might get you where you're going.

  • I'm more looking for a kind of 'catch all' hook where I already know which entity, template e.t.c would get rendered. Alternatively, is there a way to figure out if a given url would match anything craft related? I found this answer which describes how to load craft from an external app. craftcms.stackexchange.com/questions/4609/… I need something like this, but having the ability to find out if the current url matches e.g an entity or category. – Sidney Widmer Dec 21 '14 at 19:35
  • Updated answer. I think template hooks will work for you since at that point the route has been resolved and you've got access to the entire Twig context. – Brad Bell Dec 21 '14 at 22:16
  • great, thanks! I think I can work with that :) – Sidney Widmer Dec 22 '14 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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