Get Template Directory Timber/Twig
Asked Answered
W

1

6

I have a setup a simple twig template which is used to display a simple menu. I have images in here that are static and I would like use the template directory path for the image src. However when I use {{theme.link}} it appears blank. Perhaps I'm referencing something incorrectly. Code below:

<?php 
      $context['menu'] = new TimberMenu('main-nav');
      Timber::render('templates/menu.twig', $context);
   ?>

and the twig template below:

 <ul>
    {% for item in menu.get_items %}
    <li class="{{item.classes | join(' ')}}">
      <a href="{{item.get_link}}">{{item.title}}</a>
    </li>
    {% endfor %}
 </ul>
 <img src="{{theme.link}}/assets/images/test.png" alt="">

I understand that I can pass in the directory to the context but I'm curios as to why the built in function isn't working. Probably something simple. First time looking into twig so still getting used to it. Any help greatly appreciated! Thanks

Walls answered 8/8, 2016 at 20:43 Comment(2)
You forgot to fetch the default parameters from timber: $context = Timber::get_context();Tailback
@Tailback that was it, thanks for your help!Walls
W
2

@verdond2: In order to use the {{theme}} object (and its properties) you need to start with the default Timber context in your PHP file...

<?php
  $context = Timber::get_context();
  $context['menu'] = new TimberMenu('main-nav');
  Timber::render('templates/menu.twig', $context);
  ?>
Wame answered 9/8, 2016 at 14:2 Comment(1)
Thanks for the answer!Walls

© 2022 - 2024 — McMap. All rights reserved.