> Drupal 8 >

Course Overview

Login to bookmark this course

Twig Templating for Friendly Frontend Devs

Unlock Twig's full potential with our tutorial. Learn debugging techniques, whitespace control and looping tricks.

  • 4260 students
  • EN Captions
  • EN Script
  • Certificate of Completion

Your Guides

About this course

This tutorial uses Twig 1. There are newer versions of Twig, but they don't contain significant differences. So, Twig on!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": []
}

Welcome to Twig! If you're a frontend developer and you're using Twig in your project, then this course is for you! We'll talk about how to use Twig from the ground-up, clearly pointing out its syntax and then graduating to some really neat and advanced tricks. Twig is awesome to work with, so don't just use Twig, master it!

We'll learn:

  • The Twig syntaxes: {{ }} and {% %}
  • Functions and filters
  • Debugging with the dump() function
  • Handling arrays and objects
  • Template Inheritance (extends & block)
  • Tests, looping tricks, and shortcut syntaxes
  • Macros (Twig functions)
  • Whitespace control, escaping and more!

Ok, let's go!

Next courses in the Drupal 8: Dive into D8 section of the Drupal 8 Track!

29 Comments

Sort By
Login or Register to join the conversation
Default user avatar Peter Sergeev 6 years ago

there is no product-price div now

3 | Reply |

Thanks for the typo catch! We've updated activity 1 :)

| Reply |
Default user avatar Dennis Gearon 6 years ago

IT would be nice to see the before and after, textual output, and HTML rendering of same for all the filters

1 | Reply |

Hi Dennis!

Can you explain a bit more what you'd like to see and why? Are you referring to the Twig filters - i.e. having a page to see the before and after affects of applying the filters? Or are you maybe talking about the activities? If you have a few minutes, I'd love to chat - you can email me at ryan@knplabs.com.

Thanks!

| Reply |
Default user avatar Pascal Borreli 6 years ago

.product-price div does not exist

1 | Reply |

Nice catch! We've got that updated :)

1 | Reply |
Default user avatar enkuso 6 years ago

Good cast for beginners,

Now I need more advanced twig tutorial. ;-)

1 | Reply |
Default user avatar Danny Avery 6 years ago

So, I'm rendering http://localhost:8888/twig/start/templates/homepage.php and nothing seems to be connected. (i.e. Bootstrap, etc) Also, when I go to place this "<h1>{{ pageTitle }}</h1>" in homepage.php, it renders the text as follows "{{ pageTitle }}". I am kind of lost as to where to begin with this project due to a lack of clarity. Can I please get some help? Thanks!

| Reply |

Hey Danny!

I just hit you up by email, but in case anyone else has the same question, make sure you change the URL to execute the index.php file - so in your case, http://localhost:8888/twig/start/index.php. That file then executes templates/homepage.twig (so make sure you rename homepage.php to homepage.twig - we do that in the first chapter).

Also, to code along locally, you'll need to download Composer (https://getcomposer.org/dow... into the root of the project (i.e. the "start" directory) and then run "php composer.phar install".

Cheers!

| Reply |

Hey again!

I wanted to make things even a little easier, so I've just updated the code download. If you re-download, you won't need to worry about the "Composer" step above. The README.md in the code download also has details on how to get everything up and running. If you have any issues, let me know and we'll make sure we get them ironed out.

Cheers!

| Reply |
Steve-D avatar Steve-D 6 years ago

Hi

I've completed the Twig course (more than once) but it still shows as 97% complete. Are you able to see why?

Thanks

| Reply |

Hey Steve,

Probably you left a challenge as not answered or not viewed chapter, look for checkboxes opposite chapter titles in the table of content. If you're still can't find a skipped thing, let us know your email registered on KnpU and we'll help you to discover missing thing :) You can send us your email directly to hello@knpuniversity.com or via our contact form https://knpuniversity.com/c... to avoid send it publicly in comments.

Cheers!

| Reply |

Have done that Victor, thank you

| Reply |

Great! Congrats with complete completing of the course ;)

Cheers!

| Reply |

Is it possible in a twig template to add a redirect from an edit form? I am creating a news page where non-html users can fill out a form, submit and the twig template lays out the page.

That said, I want to give one option to copy/paste a URL in if they just want the headline to link to a URL instead of a page they are creating. Does this make sense...is this possible?

| Reply |

Hi there!

Actually, it's not *really* possible. The reason is that, strictly speaking, Twig just returns text. But to redirect, you need to set a 301/302 response with a Location header. That kind of logic is done in whatever layer is actually *calling* Twig.

The same seems true on your case - when I access a page (and you look up the page in the database, for example), you should determine before calling Twig that this is a page that is just a URL there and redirect in PHP.

Now, technically you *could* redirect in Twig just by writing some JavaScript and printing out the target URL via Twig inside a JavaScript string. That'd work just fine - it's a bit of a hacky way to do it, but I'm not here to judge ;).

Good luck!

| Reply |

On http://knpuniversity.com/sc..., I've tried to add the line of code "{{ dump() }}" but it still comes up as wrong. Is there an answer sheet somewhere I can check? As I'm pretty sure my answer is correct.

| Reply |

Hi John!

It looks like your answer was right - the grading was too tight! I've fixed the issue (https://github.com/knpunive... and it should look good now. The rendered dump will look a little ugly (since we're showing the HTML source, not the rendered HTML) - we'll add a rendered HTML view soon that'll make it look better :).

Thanks for reporting the grading bug!

| Reply |

Hi Ryan, cheers for the update. I think there is another small issue here: http://knpuniversity.com/sc... I don't think the product object has the "postedAt" variable sent to it.

| Reply |

Thanks again John - the activity code wasn't updating correctly. It should be better now, but I'm going make some changes yet to be sure.

Again, thanks for letting us know :)

1 | Reply |
Default user avatar TorstenMaas 6 years ago

Hi Ryan,

the Twig documentation says we have to include files mit {% include ... %} instead of {{ include('_banner.twig') }}. The challenge can't be finished either with {{ ... }}. It seems that it changed or do i miss something?

| Reply |

Hey TorstenMaas!

Great question actually - I've seen this confuse people in the past! Basically, both work, and are identical. BUT, {% include ... %} was the original syntax and {{ include ... }} was added later, and in general, is preferred. Why? Well, since {{ ... }} prints something, it makes sense just to make include() a function that you print... there's really no reason for there to be a special tag (i.e. {% ... %}) for it.

So, you can use either, but {{ include }} is preferred! The challenge should allow you to have either - if you were having issues, it may have been related to a challenge bug in a deploy that we did last night (which is now fixed).

Cheers!

| Reply |
Default user avatar Pieter Lelaona 6 years ago

great !!! owesome !!! thanks.. :)

| Reply |
Default user avatar SHirshak 6 years ago

really knpuniversity is great > thanks for the best tutorial...you gies don't know you have cleared all my confusions

| Reply |
Default user avatar capSix 6 years ago

Hello. I have a silly question. How can I render my twig templates from an array.
Example, I have rendered the parent & child templates, however if I want to link them form the nav menu, nothing seems to work. I have used the example above as I am using Twig as standalone to my project, not with Symphony.

Can anyone help please. Much appreciated. Thank you !
Great job with all the videos, btw.

| Reply |

Hey there!

Thanks about the videos :).

So when you're using Twig standalone, it's not concerned with how you create links from one page to another. It really can't be - because it doesn't necessarily know that "about.twig" lives at /about and "homepage.twig" lives at "/". So, it's your responsibility to make the links between the pages.

But, I have a feeling that I'm not actually answering your question :). So let me know if I'm not and pass more information - like what your link code looks like and any errors, etc.

Cheers!

| Reply |
Default user avatar capSix weaverryan 6 years ago edited

Hello. Thank you for you reply. Correct, my issue is to render the pages. I have created arrays in my app.php file, example:

    echo $twig->render('index.html.twig', array(
     'item'=>array(
            'home'=>array(
                  'title'    =>'Home',
                'url   '=>'/',
              ),
             'about'=>array(
                   'title'  =>'About us',
                 'url'   =>'about-us.html',
               ),
          )
      ));

Main
thing is i'm not sure how to link then from the html, i have tried
adding on the {{ item.about.url }} block, but doesnt seem to pick it up.

I'm sure it's something pretty basic and simple, but have been struggling to make it work.

As a ref I've followed your video Twig-The Basics...

Do you think you could help me out with this?

Thank you very much, really appreciated.

Thank you!

| Reply |

Hi there!

Actually, you're doing everything perfectly. I've copied your code into a gist so it's more readable (code isn't so great in the comments): https://gist.github.com/weaverryan/26c8166d16454b4c0829. And basically, what you're doing is perfect, so it should be working just fine.

Are you getting an error or just no value is printed? Also, try simply putting:

{{ dump() }}

temporarily. This will dump all variables you have access to. This will help you make sure that you have access to the variables that you think you have access to.

Let me know what you find out!

| Reply |

I really love the videos you guys put out. They're really well organized and I genuinely learn great things easily from your tutorials. :)

| Reply |

Delete comment?

Share this comment

astronaut with balloons in space

"Houston: no signs of life"
Start the conversation!