FREELessons: 2Length: 13 minutes

Next lesson playing in 5 seconds

  • Overview
  • Transcript

1.2 Twig Template Engine for PHP

In this lesson, we’ll start by writing a simple, code-only template. But you probably don’t want to mix your code and presentation like that, so I’ll teach you how to move your templates to external files. Then we’ll look at how to include templates into other templates, inherit templates from other ones, and create content blocks so that you can reuse templates for every page in your application.

Code Snippet

Here’s an example of how to render a Twig template.

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);
echo $twig->render('greeting.html', array('person' => new Person()));

Rendering a template requires two types of objects: a template loader and an environment. The environment object takes data you provide, maps that data to template variables, and renders the template.

Related Links

1.Twig Template Engine for PHP
2 lessons, 13:22


Twig Template Engine for PHP

1.2 Twig Template Engine for PHP

[MUSIC] Of course the first thing that we need to do is get twig and the easiest way to do that is with composer. Now, if you don't have composer I highly recommend that you install it because it makes managing your dependencies a lot easier. Just go to install it and you will be good to go. Now, I'm going to assume that you have composer already, so we're going to use composer require, and we want to twig/twig and 1.0. This is going to download twig into our project folder, and it's going to give us a folder called vendor. So whenever this is done we can look at those contents. So here we have vendor and inside a vendor we have this auto-load PHP. Now, we want to require that inside of our files so I have indexed PHP right here and we want to require once. And our path to vendor autoload.php. Now in order to use twig we really need two types of objects we need a loader which is used to load our templates. And then, we need an environment which is what we will use to render our templates. And we need to create them in that order because the environment depends upon the loader. So, we'll start with the loader, I'll just create a variable called loader. And we are going to New Twig_Loader_Array. Now, this is a loader that allows us to specify an array of our templates. So, this is something that could be useful in some circumstances, but for the most part we would want to use External files. But we're going to start with this approach and we're going to pass an array that's really going to have one element. It's going to have the key or index of index and then the value for this element is going to be our actual templates. And we're going to start with something very simple will just say hello and then we want something that's dynamic, so that whenever we render this template we will supply some information. That will then be rendered and displayed within the browser. So we're going to use two sets of curly braces and inside of that is going to be our variable name. So whenever we render this template, we are going to call it index and we are going to specify a name value. And, if we wanted to specify another template, we would just give it a different name, and then a different template. But we're just going to stick with this one and we are going to create our environment and I'm going to simply call that $twig. We're going to new up Twig Environment and we are going to pass it our loader. Now, we can also pass in an optional array for the second argument that will configure our environment. If we wanted to set up some type of caching, so that our templates and rendered output would be cached we could do that. But we're just going to keep it simple and pass in our loader. So now we have our environment we just want to render our template. So, we are going to echo and we're going to use our Twig Environment. And this has a method called render and we tell it two things. The name of the template that we want to render, index in this case and then our value which is going to be an array. We need to specify a name and in this case the name is going to be a Twig. So let's save this, let's go to the browser and we will refresh the page. Hopefully we will see Hello Twig. And we do but let's add some complexity here. Very rarely do we deal with data this simple. A lot of times we're dealing with objects or at the very least, we will have an array that contains a variety of data. In this case, we're going to add a class and I'm going to do this inside of this file. Normally, I would do so in an external file but I'm just going to keep everything together here. It's going to be called Person and we're going to have two properties, firstName and lastName. And I'm going to go ahead and set values for these properties. So, first name is set to John, lastName is set to Doe. And we are going to create a Person Object and use that as the data that we are going to display within our template. So the first thing we need to change is the data that we are passing to the render method. So we no longer have a name here we have a person, so I'm going to change that to person although the name is arbitrary. We could call it through if we wanted to that's just how we are going to access that piece of information inside of our template. So in this case it's going to be a person and instead of just a normal string we're going to new up the person constructor. Now we need to be able to access the first name and last name properties inside of our template. Otherwise, there's really no use in passing in an object as her data. So to do that, we use our key name, that is person, and then we use the dot, and then the property that we want to display, first name, and we would do the same thing for last name. So as far as syntaxes concerned, it looks a lot like JavaScript where you have the object dot property. And so, if we go back to the browser and refresh, we are going to see Hello John Doe now. Now, for the most part our templates are going to be stored in extra no files. There are some cases where we would want to hard code those inside of our code but for the most part they are going to be external. It just makes sense to do that. So we're going to start changing our code to take that into account. And we're going to start by creating a folder that's going to create our templates. Now, the folder name doesn't matter because whenever you create the loader objects you tell it the path of where all of your templates are. But I'm going to call it templates because that makes sense. And I'm going to create a new file called greeting HTML and we're going to take our existing template this Hello and then the person's first name and last name and we're going to use that as our template for greeting HTML. Now we can leave this as is but let's add some HTML. I'm going to wrap everything with an opening and closing p element. So this is going to be our template. And the inside of index.php, I'm going to copy this and paste it, first of all, and I'm going to rename the copy to be loader_array.php. Array just so that we have that in the code downloader and we can now start messing up the code within the index.php. So the first thing we want to change is, instead of creating this Loader Array object. We wanna call Twig_Loader_Filesystem and instead of passing in an array, we pass in the path to the folder of where our templates are stored. So that is simply going to be templates in this case. So this is going to load all of our templates and for the name of our templates it's actually the name of the file name. So instead of index, we have greet.html, and there's really nothing else that we need to do here so we could go to the browser and refresh the page. Now, as far as what we see it doesn't look like anything changed but if we look at the source code. We see that we now have the P element the content is the same but the difference between what we had before and what we have now is that P element. Now that's all well and good but the template that we have now is more of a partial template it's just a smaller piece, of what would normally be a larger web page. So let's start to moving towards that idea. The first thing we need is a file that's going to contain basically the skeleton of our website is going to have the HTML the head and body tags and the C.S.S. and things like that. So I'm going to add a new file inside of the templates folder called index HTML and I'm just going to paste in the bare bones of this application. And for right now, we are going to include our greeting template. Now in order to do that, we use the two pairs of colored braces and then we would say include and then our template that we want to include, greeting.html in this case. Now the nice thing about this is that we don't have to pass any information to this template. It's going to automatically assume the context of this outer template. So whenever we call the render method we are still going to parse in the same data, but instead of greeting.html we are going to specify index.html. And that is going to pull in greeting and it's going to use the data that we passed. So that same person object in the first and last name and we see the results here in the browser. If we view the source, we now have the complete HTML not just the little snippet that we had before. But that doesn't really give us what we want because any time we use our index HTML template, it is always going to include the greeting template. Instead, we want the index template to be more like a layout page. Something that we can put all of our JavaScript, CSS and the markup that's going to be shared between all of our pages. So it's more like a base template in that sense and Twig gives us the ability to do that. What we need to do is define blocks with in our template that we will then supply contents for. And to define a block, we start with a pair of curly braces and then before the closing curly brace and after the beginning curly brace, we have a percent sign. And we use the term block and then we name that block. Now since this is inside of the body elements I'm going to call this block content because that's where our content goes. So we have the beginning of our block, now we need the end of the block. So we do essentially the same thing but we say endblock and now inside of our greeting template. We can say that we want to use the base template of index HTML except the actual terminology is extends. So you can think of index HTML as our base class if you will and a greeting HRTML is going to extend that class. So we say extends and then the name of the template that we want to extend. And then, we need to specify the blocks that we want to supply content to. And we do that with the same syntax that we used, in index HTML. So, this is the main content here so, we're going to say block content and then we will close that block with the end block directive. And then, now, whenever we go back to index.php, we aren't using the index template. Instead, we're using the greeting template. And whenever we go back to the browser and refresh we see the same thing that we did before. But let's add something to our index. Let's do something rather silly and let's say that within h2 element that the site nav is here, and of course it's really not here. But this will at least show us what is inside of index HTML and then what is inside of greeting HTML, so let's refresh. We have our h2 the site nav is here and then we have our content. So as you seen Twig makes it very easy to separate your HTML from your PHP code. Now of course, we couldn't look at every aspect of Twig in such a small amount of time, so I encourage you to spend some time with Twig documentation. It is very well done. Thank you so much for watching and I will see you next time.

Back to the top