0

I'm creating a template which is supposed to be as generic as possible, in pure twig (.twig files only, no php code). My main goal is now, when I have a given directory X, like:

X/
X/file1.twig
X/file2.twig
X/file3.twig

I then use another target file Y where I include all of the files of the directory X. I want that to be as generic as possible, meaning that if I for example add a file4.twig in X, it should be included in the target file Y automatically. For this, I need some kind of file iterator in twig. Is this available?

DevelJoe
  • 856
  • 1
  • 10
  • 24
  • 1
    Everything you can do in `PHP`, you can do in `twig` *if* you write/register an [extension](https://twig.symfony.com/doc/3.x/advanced.html#creating-an-extension) though. (It's not because you can, you should though) – DarkBee Oct 26 '21 at 09:52
  • I'm actually not able to run PHP code in my .twig files.. Nothing happens at all if I write code like what you've linked, and I doubt that there's no built-in tool to iterate over a file directory in a templating tool ??? – DevelJoe Oct 26 '21 at 10:15
  • 1
    Why would this be included in a templating engine? Templating engines are used to output data received from a controller. Anyway, you should reread the documentation I've linked. The `PHP` code does not go in any template. It's an entirely different class which you need to register in `twig`, then you can use the registered functions/filters/tests/... inside `twig` with the registered name of the function/filter – DarkBee Oct 26 '21 at 10:24
  • Sorry I totally don't understand your answer. How do I register it in twig? And what the function does, is written in PHP (as it looks in the docs)? So I actually need a PHP interpreter? – DevelJoe Oct 26 '21 at 10:30
  • if you could for example just provide me with a simple extension (single function) example, that would be really helpful. – DevelJoe Oct 26 '21 at 10:32
  • 1
    You are using `twig` standalone? If so, create your extension class and register it with `$twig = new \Twig\Environment($loader); $twig->addExtension(new Project_Twig_Extension());` – DarkBee Oct 26 '21 at 10:32
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/238545/discussion-between-develjoe-and-darkbee). – DevelJoe Oct 26 '21 at 10:32
  • 1
    See [here](https://stackoverflow.com/questions/45724016/how-to-create-an-extension-using-twig) - Not sure which twig version you are using but the principle is the same for twig3 – DarkBee Oct 26 '21 at 10:33
  • I'm not getting it, sorry; the thing is I'm not even on a server. You may check what I've written in the chat – DevelJoe Oct 26 '21 at 10:41

0 Answers0