Mark Fox
Mark Fox

Reputation: 8924

Can I refer to "ThisBundle" in a twig template, instead of hardcoding a bundle name?

I'd like to be able to implicitly refer to the current bundle from within a twig template; normally you'd see:

{% stylesheets '@AppBundle/Resources/public/css/main.css' %}
    <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
…
{%- include 'AppBundle:Alpha:nav.html.twig' -%}


But, instead of harcoding AppBundle I'd like to generically say ThisBundle:

{% stylesheets '@ThisBundle/Resources/public/css/main.css' %}
    <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
…
{%- include 'ThisBundle:Alpha:nav.html.twig' -%}


Is something along these lines currently possible?

Upvotes: 0

Views: 123

Answers (3)

Cerad
Cerad

Reputation: 48865

Of course you can do this. Start by reading: http://symfony.com/doc/current/cookbook/templating/namespaced_paths.html

The twig name space processor does not actually care (or even really know about) bundles. Instead, it maintains an array which maps @whatever to one or more location where it looks for the desired file.

By default, the symfony TwigBundle:DependencyInjection:TwigExtension class adds all the existing bundles to this array. It's instructive to review the code.

All you really need to do is to add your paths to config.yml

twig:
    debug:            %kernel.debug%
    strict_variables: %kernel.debug%
    paths:
        "%kernel.root_dir%/../src/Cerad/Bundle/AppBundle/Resources/views": ThisBundle

Of course there is really no such thing as a "current" bundle. You still need to set the resource path as shown above. But I'm pretty sure this will suit your needs.

Sorry for all the edits. For this to work you do need to use twig namespaces exclusively. So something like:

{%- include '@ThisBundle/Alpha/nav.html.twig' -%}

Upvotes: 3

Pier-Luc Gendreau
Pier-Luc Gendreau

Reputation: 13814

No it is not possible.

However, you could make a CoreBundle where you store generic templates like navigation and site-wide stylesheets.

Upvotes: 2

Wouter J
Wouter J

Reputation: 41934

No, you can't. And there really is no real use case in which you should be able to do this. A bundle knows it's own name, as it knows it's bundle class (which is the name) and at least it knows the namespace, which is the bundle name... There is no way to change the bundle name without changing the bundle.

Upvotes: 1

Related Questions