Mastering Home Assistant Templates: A Beginner's Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're talking templates if you're not already using templates inside of Home assistant getting started can be extremely intimidating but those templates can also be extremely powerful so in this video we're going to cover what Jinja is as well as some template basics we're also going to talk about how to leverage home assistant entities inside of our templates and even how to transform those entities using some ginger functions so by the end of this video you should have everything you need to get started using templates in home assistant so stick around because this is definitely going to help you automate the boring stuff [Music] back to soccer Labs my name is Jeff to build a smart home using home assistant you don't have to be a programmer and you don't have to have any programming knowledge but there does come a point in your journey when knowing some programming can be useful especially when you start talking templates but don't worry you don't have to have any programming knowledge to follow along with this video this video will be a bit longer than my normal videos but it's meant more to be a guide and to help with that there are timestamps below so you can jump around as needed first off let's talk about some changes to templates the new release of Home assistant which as of this video is 2023.4 is bringing us lots of cool new templating stuff we're getting the ability to create macros and some new home assistant specific functions that will make it much easier to leverage a group of entities inside of Home assistant I'm definitely excited about all of these new features but it doesn't really change what I was going to discuss in this video but I do plan on doing a follow-up video to this one where we cover more advanced templates and some of these new features are definitely going to help with that for now though let's just start with the basics in home assistant templates use ginger or specifically Ginger 2. although most of us just refer to it as Ginger Ginger is a template engine and its purpose is to give us access to programming functions inside of text files like HTML files in home assistant those dreaded yaml files are just structured text files that format information in a way that the python code that runs homosystem can easily read them and so that the humans that might modify that information can easily read it as well Jinja just allows us to act on that information in a way that you couldn't do with just text for example Jinja allows us to reference other information inside those text files or information outside of those yaml files to provide context to that information making what would be just plain text a little more Dynamic and it allows us to do other things that wouldn't be possible with just text like math and decision logic like if else statements it's Dev definitely easier to write templates if you know python but Jinja doesn't require you to be a python expert in fact you don't really need to have any programming knowledge at all to create a template I don't want to give you a huge list of things to memorize but before we get started I do want to cover some template basics foreign before we go any further I just want to mention that any of the examples I'm going to show in this video might not be super practical in an actual smart home or the best way to create a template for this specific purpose I'm showing they're simply meant to show the basics and how to create a template in home assistant and with that some of the functionality I'm going to show already exists in home assistant core without the need to create a template and you never know others may be added to core in a future release anyway one of the tools you're going to use a lot especially when you're starting out is this panel in developer tools this template area allows you to test templates in real time so you can see the output before you actually write it into yaml somewhere it does come with some nice demo info that can show you some of what you can do but for now we're just going to clear this if you ever want to get this back just click this reset to demo template at the bottom first the basic thing you'll need to store in your memory are these curly braces this is the version of ginges print statement for example if I type hello between these curly braces I'll get an error because we have not defined the value of this word hello and Jinja thinks it's a reference to another value if I wrap hello in quotes you'll see that Jinja understands now that this is a string of text and its value is hello but this is a smart home so using static values like this doesn't really make sense we want this data to be dynamic or set up in a way that we could change it on the Fly because that really is the beauty of templates so let's change this string to the word greeting again Jinja expects the value of greeting to have been defined because when not wrapped in quotes Jinja sees this as a reference for another value but Jinja does give us a way to define or assign a reference to this word which brings us to the other set of curly braces you'll see the curly brace percent sign denotes an area of code what is in between these two tags will be executed but the result will not be visible outside these tags unless we use that print statement so if we use the command set followed by greeting equals and then in quotes the value we want to save to the greeting like hello comma can you see me now as soon as we close the quote our string will be visible and just to illustrate the difference between these two sets of braces if we remove the second line you can see that even though we've defined the value of greeting there's nothing here that tells Jinja that it needs to display that information now before we get into how to leverage this with home assistant specifically let me show you a pattern that you might use from time to time which is to combine a stored value and some static text if we move the comma can you see me now down to our second line and put it after these last curly braces we can now change our greeting on the Fly for example change the value of greeting to hey which changes the message this template displays which is an extremely useful pattern when building smart home templates because the entities you reference are going to change and in things like text to speech or text notifications or even on your dashboard where you want to display a message you can leverage this so that templates are dynamic so let's see how you might use these Concepts in home assistant most of the time you're going to be creating templates inside of a yaml file somewhere because as of the 2023.4 release of Home assistant there's no way to create templates inside the UI and if you want to use templates inside the automation or the script editor then you're going to have to switch to the yaml edit mode to be able to leverage those templates so for this following section I'm probably going to be jumping between this template panel inside of the developer tools and some yaml files but don't worry about trying to copy the code off of this screen because in the description of this video are links to the code I'm using either in the developer tool panel or in the yaml code itself anyway one of the most common ways I use home resistant templates is to reference either the state of an entity or an attribute of an entity for example maybe I want a template to include the friendly name of an entity along with its state which could be helpful if I want a notification that the front door is currently open Home assistant has some built-in functions that can help with that they are state and state underscore ATT so let's say you want to get the state of one of your entities it's as simple as using our double curly braces States parentheses single quote and then the name of an entity like light dot desk underscore backlight single quote close our parentheses and then the closing double curly braces as you can see we get off as the current state and if we didn't change anything else if the state of this light changes the value of this template changes as well if you want to get the value of an attribute then you would use State underscore ATT es single quote again the name of an entity like light dot desk underscore backlight single quote then a comma another single quote and then the name of an attribute like energy single quote and then close our parentheses and then those closing curly braces which displays the current energy value which is 69.79 so now let's say you want to create a new template sensor using that energy attribute so you could display it on a dashboard we could add this to our sensor.yaml file platform colon template then under that sensors colon then under that we're going to indent and type the name of the entity you are creating in this case desk underscore light underscore energy this will be the entity ID of our new sensor then under that we're going to indent and Define a friendly name using friendly underscore Name colon and in double quotes the name you want to use this will be the name that is displayed on the dashboard by default then under that value underscore template which will be double quotes then our double curly braces State underscore attr parentheses single quote light dot desk underscore backlight single quote comma single quote energy single quote close parentheses close double curly braces now if we save that and reload our yaml defined templates you should now have a new sensor and now if you wanted to use this new sensor in a notification that gives you the current usage of this sensor you can create a template like this in which we have a sentence written in text and in place of our entity name we use this template which gives us the friendly name of an entity and also a template that gives us the energy using that sensor we just created which combines everything we just discussed into a line of text that can be dropped into the message attribute of a notification script and provide a readable notification and again each time the energy changes so will this template of course we didn't need to create a template sensor for this specific example but I hope it gives you an idea of how you could use these two Ginger functions to create a more complex template or at least as the start of a completely new sensor you could just use the states and the state underscore attr function since we're referencing existing entities and Skip creating a new sensor altogether but there are times in which you're going to want to create a new sensor especially if you want to transform that data which is where the power of templating comes in since the whole purpose of Ginger is to make text more Dynamic Ginger provides a lot of functions to help us do that the biggest is probably the ability to do math on values we pull out of these entities and again these examples are more focused on things that you could do not necessarily things that you're going to want to do or even need to do since home assistant does some of this for you already but hopefully it Sparks an idea of how you could use templates inside of your home assistant setup okay let's say you have an entity that has temperature we can use the curly braces along with the state's function and the name of our entity to get the current value since I'm in the United States this sensor is currently in Fahrenheit but converting it to Celsius is super easy especially if you want to display both versions on a dashboard inside our curly braces here we can do some math and hopefully you remember your order of operations we can subtract 32 from our Fahrenheit value divide by 1.8 and get Celsius but as you can see it gives us an error and that brings us to one of the most important things to remember when working with home assistant entities inside of templates all states are stored in home assistant as strings and you can't do math on a string and a number or integer which is what this error is trying to tell us so anytime you do math with a state that appears to be numeric you need to make sure that you convert it to an integer and we can do that like this after that closing parentheses we can type space pipe which is the character above the return key another space and int for integer and there it is we have our value in Celsius but this is way too many decimals so we can use round and at the end let's type space pipe space round and as you can see the value changed but if you were paying attention to the value before and the value now and understand the fundamentals of rounding numbers you'll know that this didn't work as expected based on the previous value this new one should be 18. but our pipe round we added made it 16 and again this comes down to that pesky order of operations that's been confusing people on those Facebook math posts for what seems like forever as well as how pipe Works in these templates that pipe character is telling this template to take the value that precedes it and pass it to the function or the value after this allows us to get a value transforming and then take the new value and transform it again so this pipe int took the value of the entity before it which was the temperature as a string and turned it into an integer this pipe round is taking the value of 1.8 and rounding it to 2. but that isn't what we want so we need to wrap the entire equation in front of this pipe in parentheses so that our template gets the results of this entire equation before rounding it and when we do that we get the expected Behavior 17.77 repeating of course becomes 18. but round is also pretty flexible because we can add parentheses after round and give it a number of decimals we want so if we add parentheses 1 after round the result is now 17.8 and if you made that a 5 you would get 5 decimals of precision this is one of those Ginger patterns I use a lot now if you wanted to create a new sensor with this value we would just need to jump over into our yaml and either in our sensor.yaml file or our configuration diamo or even a package where we have a sensor colon heading we can now create a template based on the entity like this under dash platform template and then sensors colon we're going to give it an entity name like basement underscore temp underscore Celsius a friendly name and then wrapped in double quotes the template we tested in that template panel now save and reload your template entities and now we have our new entity that can be used anywhere we want although it looks like I left an extra double quote in there or I guess I only included one for friendly name you can wrap it in double quotes or not only including one isn't the best unless you like that the value template always needs to be wrapped in quotes because again home assistant expects the value of any entity state to be a string or you could skip the quotes and put a greater than sign and on the new line put your curly brace template without the double quotes wrapped around it [Music] okay I think that should give you enough to get started but before we end this video I wanted to give you some other examples of Ginger patterns you might use some of these examples I'm going to show you are going to be more advanced than the previous ones I talked about and I'm also not going to go into depth on each one because I don't want this video to be an hour long but I also don't know in my Advanced template video will be out yet and just to make sure that you have even more information if you already know the basics I wanted to include these just to help spark ideas so one of the things I wanted to talk about real quick was this stats panel which I get asked about a lot because I've shown it in a couple of videos it's simply a count of some various entities like the number of binary sensors the number of devices lights and so on and these are all template sensors I've set up so let's flip over to my yaml configuration and this ring here is the templates that power that panel so I created a sensor for each one of those and they all follow a very similar pattern so in this case we use that states.sensor to get a list of all the sensors we pipe that to this reject attr which we really haven't talked about and we'll go in more depth in the future video but what this is saying that is we want to reject any device in states.sensor that has a state equal to unavailable now this is one of those in which the syntax is not all that intuitive but a link I left in the description on where you can get more Ginger details they go into depth about the different options you can use for this entity or this middle section of this template then we get a list of anything that is not unavailable we pipe that to this function list which lists everything out and we get the count so just to show you what this is doing let's jump over to that template panel real quick and we will put this guy in so if we started out here with just States dot sensor in that template we get just the domain sensor which isn't all that useful but if we pipe this to list you can see it gives us a list of every entity that is set up as the type sensor and it lists every one of their attributes in this list which can be a lot now that also means that every one of these attributes is accessible through a template but we'll go into that again in the future video because that can get really crazy on how to dial into a specific one of these attributes from this list but if we wanted to take this list and simply get a count of all of the devices we can now pipe that list straight to count but of course my smart home like probably everyone else is out there using home assistant has a lot of Those sensors that are either old or abandoned or simply unavailable and if they're unavailable we don't want to include them which is where that reject comes in so if we add in that reject att-r then pipe it to list then to count we get that 707. all right let's flip back to my yaml and I can show you some more of those templates real quickly so if we scroll down here you can see that I have a couple of these sensors that I created one is today is and one is month is and I use these in various notifications and also use it as a condition in some of my Automation and then I can just use this sensor dot today underscore is in any place where I want to have the actual name because at one point this sensor did not exist inside of Home assistant maybe it does now but I'm not real sure in any case this is how I've set this up I've got this template which includes a list of all the days of the week a list is in how python defines a list which is this bracket and then comma separated values and then I use this Now function with the weekday here to pick exactly which one of these values in the list it is over a complicated way to get to the actual name of the weekday but as far as I know I think this is the only way you can do that inside of Home assistant I mean I could be wrong and if I am please include that in the comments I also have one for month which gets a little more complicated in how months are set up and how lists work in Python so we have to use a little different syntax here we have to take the numeric value of the current month which is what this now parentheses dot month would get us and subtract 1 because there's no zero month whereas weekdays there's a zero weekday anyway that gets a little more complicated into Python and how lists work but but if you want a sensor that can tell you what the day is or a sensor for the month this is one way you can do that but I also use templates to randomize some of my messages which you've probably seen before and Jinja has a handy function just like this count and it's called random so if we flip over to some of my notification scripts in fact this is the one that gets triggered anytime my Sentry mode or security system is armed and it randomizes a message so here we've got another list which has a bunch of sentences in it and then this pipe random just picks a random one out of this list every time it gets called so every time this automation fires this template here just helps me randomize that notification and this pipe random comes in handy in lots of different ways and in fact you see it a lot and I talk about it a lot as randomizing text-to-speech notifications but you can also use it to randomize other values that you might pass to another service call for example I use that random function to randomize music so here I've got a simple script that plays a random audio track from my Disney park audio that I've collected from various parts of the web or from YouTube and anytime you call this script it just randomly picks one of these sources for music and plays it okay we've covered a lot and there's definitely more to talk about especially in regard to Advanced templates and like I've said multiple times in this video I hope to have a video on that in the future and hopefully soon as always if you have questions drop a comment or hit me up on the social media and please if you have a template topic you want me to cover in the next video let me know in the comments of this one as well I have links to the yaml examples we talked about in the description of this video as well as a list of all of the code I showed off in that template panel and even some links to Ginger resources that you might find helpful when trying to figure out how to build a ginger based template if you're looking for more home assistant videos from me check out this video which YouTube thinks would be perfect for you now it's time for us to go automate the boring stuff foreign
Info
Channel: SlackerLabs
Views: 41,589
Rating: undefined out of 5
Keywords: home assistant automation examples, home assistant basics, home assistant for beginners, home assistant beginner's guide, smart home ideas, home assistant tutorials, smart home tech reviews, advance home assistant automations, build a smart home, home automation for beginners, home automation tutorials, home automation tips, home assistant ideas, jinja, home assistant templates, getting started with home assistant templates, home assistant template basics
Id: m1aqyX6LXlo
Channel Id: undefined
Length: 23min 55sec (1435 seconds)
Published: Fri Apr 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.