Basics of Go

Go Templates

Maximiliano Firtman

Maximiliano Firtman

Independent Consultant
Basics of Go

Check out a free preview of the full Basics of Go course

The "Go Templates" Lesson is part of the full, Basics of Go course featured in this preview video. Here's what you'd learn in this lesson:

Maximiliano explores the usage of Go templates for server-side rendering, emphasizing their ability to generate dynamic content like HTML or configuration files. By separating the presentation logic from the data, Go templates facilitate easier management and updates.

Preview
Close

Transcript from the "Go Templates" Lesson

[00:00:00]
>> For that, we are going to use something known as Go Templates. Go includes a template framework, a template is a format that we use our strings with some kind of a little language inside, if you're using Angular, for example, you know what a template is, when you define the template, your HTML file is actually a template.

[00:00:25]
You can insert a special tags that are not the HTML within that template, if you're using React, JSX is kind of a template. It's not really formally a template but kind of, and in Go, it's not specifically targeting web pages, you can use it for any string. But most of the time we use templates for creating server-side rendering.

[00:00:49]
This is similar, in case you have ever played with PHP, for example. You mix, and I'm talking about playing vanilla PHP without the framework, without the templating system. You write the dot PHP file and you mix with HTML with PHP code in the middle, okay? It's kind of the grandfather of templating.

[00:01:10]
Anyway, so in this case, we're going to create an HTML file with some Go code in the middle. Some, it's a template actually, so it's limited, it's restricted to some ideas. It's actually in the HTML package, and the template can include expressions using double curly braces. So if you are coming from Angular, you will feel at home because that's how interpolation works in Angular.

[00:01:39]
So you will see this in action in a second. Also, there are some options where you can trim spaces, I will show you what that means because it's not completely clear. We can mix actions and pipelines as well, this is more complex, we will just cover the basics, the fundamentals, but you can call functions and you can use pipes to define how the output will look like, okay?

[00:02:06]
On Angular you also have pipes on templates that are kind of similar. So for example, you wanna render a price, well, you can parse that through A pipe that will add the currency, the character, like the dollar sign or the euro sign. And then you can parse for another pipe that can format the number with two digits, and then you can go for another pipe that can convert into Bitcoin.

[00:02:30]
So you have a pipeline and you are parsing that data, the input for different processes. So you have that, you can do if-else not in the Go file, but in a template and you can do range for loops. Okay, so it's like an ng4 for Angular or when you're doing a map on JSX.

[00:02:56]
And you can also call functions that you have on your Go file. So, let's make one. So for that, we're going to create another folder, I could create the template in the public folder, but if I do that, it's going to be served if someone knows the URL.

[00:03:17]
So yeah, I don't wanna make that public, so I can create a new folder. Maybe we can call that templates and I can create a template for an index file. What's the extension for templates? We don't have one. Some people are just saying HTML, some people say dot template, dot Tmpl, wherever, yeah, it's up to you.

[00:03:40]
And for example, I will take my index HML and I will copy and paste my index HML and I will convert that into a template. Because it doesn't, BS code doesn't know what that is. At least you can, if you save it actually, if you look at the bottom BS code, actually saying that this is a gold template file, so it's recognizing that we are in Go and that extension is one of the tension that we typically use, but you can change that to HTML in case you wanna see colors again.

[00:04:11]
That's actually, your change has your IDE. So it recognizes that file as HTML, or you can just keep it at as a Go template. So then it will support, basically when you open that thing it can recognize the tags and and so on. Anyway, I didn't want that.

[00:04:37]
So, let me just put HTML so we can see, this. So as I mentioned, I'm going to get rid of the script yes, so we won't have JavaScript, I don't want JavaScript in this. I have here an article that I will use it as some kind of Templates, okay, so we can kind of feel that thing.

[00:04:59]
So once idea at any time in this template, I can open double curly braces and add an expression. Typically, what you're going to do is you're going to receive an object that you use here as your, let's say it's kind of your source of information, so. But that's a template, so it's still empty, right?

[00:05:27]
How do you use a template? Well, here we have an example of how the code looks like, we're going to write a code anyway. So, we're training you to create a new template using Factory. So template.new from the template package. Template.new, we set the name, and then we can parse a template.

[00:05:46]
What's a template? A string, that we can read from the file as well. So it can be a string that we set statically or we can read it from a file. And then at some points, we will have expressions. And actually when we execute, we can execute the template, we're going to parse an object, actually a value, that is going to be used within the template as the source of data.

[00:06:15]
And you access that value with the dot. So if it's a structure, you use dot and then the name of the property. In this case, it's going to take the name of the person. Does that make sense? You can execute a template to a string. So you can receive a string in return.

[00:06:33]
And you can also write the template directly to the output of a writer or for server. So there are several methods available. Do you wanna get the string, that mean the result of a string? You can use that for example for sending emails, you have a template, and then you can send bulk emails, emailing.

[00:06:53]
And then you have the template, and the template can include some kind of logic inside, such as if conditions and loops, that's kind of the idea, okay? So just to play with this, we are going to back to our goal and we're going to add another handler. Let's create the function first, let's call this handle template.

[00:07:15]
It's the same as before, we're going to receive a brighter, so response writer. And we have also the request, the http request, handle template, and we are going to call that handle template, for example, we are going to handle that and we can just for now, for playing with this as a playground, we can say forward slash template, handle template.

[00:07:43]
Okay, so yeah, later we'll replace that directly with the index HTML. So you will remove, we will delete the index HTML from the Public folder and we will just serve the template version. So, the first thing that we're going to do, first, I can create a template from a string, okay?

[00:08:06]
But in this case I'm not going to create the template as a string. I'm saying this, I guess you can say, okay, my template is HTML and then I'm going to write the name of the user, but I'm not going to do that for that I have a file, an external file, okay?

[00:08:20]
So instead of doing that, I'm going to call template.ParseFiles that is going to do all the file system thing for me and I'm going to parse templates/index.tmpl, and it's going to return me the HTML template, let's call it HMTL, and a possible error. In case the file is not there, we don't have permissions to read the file or something like that.

[00:08:52]
We can validate the template before trying to use it. There is a, just to know, there is a template Must, where you parse a template, and it will actually. It's like a wrapper, so it's kind of a high order function that actually verifies if the template is valid before executing it, because if you execute a template and then template is invalid it will crash your app, it will panic, okay?

[00:09:25]
So to avoid that we can first go through Must but I wanna make it simple first. So if we can actually do something, so if. Error is not nil is because we have a problem, okay? We do have an error, so something that we can do at this point is we can write.

[00:09:49]
We do have a Write Header, in the Write Header we can actually send an HTTP status quo, so we can say, for example, Internal Server Error, that's 500. Something has happened in our server, it cannot serve you the file. And you can also write some text to the output as well, as slice of byte.

[00:10:11]
So you can say something like Internal Server Error, like that? If not, it's because we do have the template, okay, so we can use cells or we can just continue and maybe call return. Or, if everything is correct then I can try to execute, the template, and the first argument for execute, we have execute to a string or we can execute to the writer.

[00:10:39]
And what's the writer? The argument that we will receive here, the output of the server, and. We have parsed w there. And then the object, that we wanna parse, for example, for now I can just say Test. I can parse a string, the value that they want the template to parse, okay?

[00:11:08]
So, our our index the template has, this is going to be invalid. Actually, let's see what happens if I execute this. So if I stop my server and run again, and now I'm going to localhost forward slash template, I'm receiving an internal server error, okay? Why? Because, the template is invalid.

[00:11:36]
Why? Because we have that empty expression, that's why it's not working. By the way, if you look at the cursor here, I have a Write Header error, it's saying me that, I'm saying the 500 is not working. Why? Because I'm sending the Header after writing content. And on HTTP, it is a buffer, the code goes first.

[00:12:04]
So if you have already sent somebody to the client, you cannot change the HTTP code. Does it make sense? So if you wanna send that status code, you need to do it first before sending any content to the browser. That's how the HTTP protocol works. So what if we wanna render that Test string within the template?

[00:12:33]
It's kind of weird, it dot. Dot is actually the value that you have received as input. You can see well dot is just that, what if I wanna parse something else, like a second, value? You cannot, it's only one value, that's the idea. Well, you can create a structure with everything you need to parse, or you can parse in a slice.

[00:13:00]
Make sense? Typically, you create an object and a structure that you parse to the template and you render for everything. That makes sense? In some way shouldn't see that, WriteHeader error anymore. So if I refresh, you can see I have my Test string embedded into the HTML. So it's actually in the source code of the HTML, we have that Test string that is coming from a Go value, a Go variable, okay, makes sense?

[00:13:38]
So that's the basics of a template. It's not a big deal, that dot looks weird, but at the end you get used to.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now