2

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?

Czechnology
  • 14,832
  • 10
  • 62
  • 88
  • Nothing keeps you from writing a custom function that returns the respective path to your file. – Raffael Sep 26 '11 at 18:36
  • @Яaffael1984: I'm not sure if I made my question clear - some text comes from txt/html files or database string/text fields. I'm looking for a way to parse these files - that is to add the correct path where required - that could be considered a correct symfony2 approach. – Czechnology Sep 26 '11 at 21:03
  • Hmm, interesting question. The best bet would probably be to create a couple of Twig extensions. I'll try to whip something up tomorrow. – kgilden Sep 27 '11 at 00:44
  • @gilden: What do you have in mind? Something like `{{ content|parseExt }}`? That's definitely possible, my question only is if this is the "nice" way to go. I'm sure I'm not the first one with this problem. – Czechnology Sep 27 '11 at 07:42
  • Yes, that's pretty much the idea, but instead of a filter I guess it would be nicer to use a function: `{{ file('@AcmeDemoBundle:Foo:index.txt') }}`. This file would be at /src/Acme/Bundle/DemoBundle/Foo/index.txt and the function would print the contents to the template. Most elegant solution in Symfony2 I could imagine :) – kgilden Sep 27 '11 at 10:17
  • @Czechnology I have finished making a working prototype. It will now take some time to set up a public repository on GitHub. Since this is my first, I'm not sure how long it'll take. – kgilden Sep 27 '11 at 20:14

1 Answers1

3

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.

kgilden
  • 10,336
  • 3
  • 50
  • 48