Czechnology
Czechnology

Reputation: 14992

Using "path" and "asset" for non-template data

When creating templates with Twig, it's easy to use the path and asset functions.

<a href="{{ path('my_route') }}"><img src="{{ asset('bundles/acmedemo/my_image.png') }}" /></a>

However, some of my data come from non-twig files or from database. What would be the right way to address these functions from there?

So far, I'm using regex replace (preg_replace_callback) for the path function. But isn't there a nicer way?

Upvotes: 2

Views: 3770

Answers (1)

kgilden
kgilden

Reputation: 10346

I am proud to present my first public mini-project, the StaticBundle. It pretty much lets you include any file in a bundle straight into a template.

Setup

EDIT The bundle can now be installed using composer, please see the instructions on readme.

Add the following to deps:

[KGStaticBundle]
    git=git://github.com/kgilden/KGStaticBundle.git
    target=bundles/KG/StaticBundle

Run bin/vendors install.

Register the namespace in app/autoload.php:

'KG' => __DIR__.'/../vendor/bundles',

Register the bundle in app/AppKernel.php:

new KG\StaticBundle\KGStaticBUndle(),

Basic usage

Suppose we have a file src/Acme/Bundle/DemoBundle/Static/hello.txt ready to be included in a template. We'd have to use a file function:

{# src/Acme/Bundle/DemoBundle/Resources/views/Demo/index.html.twig #}

{{ file('@AcmeDemoBundle/Static/hello.txt') }}

The logical name gets resolved into the actual path and a simple file_get_contents retrieves the data.

Upvotes: 3

Related Questions