Welcome to Python Template Class Tutorial For Beginners. In this post we will learn template class of string module in python. We also learn, how and why we use templates in python. So start learning without any delay.
In general term – A template is a file that serves as a starting point for a new document. When you open a template, it is pre-formatted in some way. For example, you might use template in Microsoft Word that is formatted as a business letter.
But here we will discuss python templates.
Python Template Class Tutorial – Learn Template With Examples
What Is Template ?
- In python, template is a class of String module.
- It allows for data to change without having to edit the application.
- It can be modified with subclasses.
- Templates provide simpler string substitutions as described in PEP 292.
- Templates substitution is “$“-based substitutions, rather than “%“-based substitutions
How It Works ?
- Template class takes a string as a template, within the string use placeholder variable name with preceding the Dollar($) sign to depict there is the placeholder.
- Then substitute value into the template with substitute() method using a dictionary. Where key is in the dictionary match with placeholder name. The returned string is the template with all the values rather than the placeholder
- It should also be noted that, the placeholder variable name should also be follow the same naming convention as variable naming in python.
Substitution Rules For Python
For performing substitution we should have to follow the following rules –
- “$$“ is an escape ; it is replaced with a single “$“.
- “$identifier“ names a substitution placeholder matching a mapping key of “identifier”. By default, “identifier” must spell a Python identifier. The first non-identifier character after the “$” character terminates this placeholder specification.
- “${identifier}“ is equivalent to “$identifier“. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as “${noun}ification”.
How To Implement Template ?
Now we will define a template and see how it works. So write the following codes for implementing template.
1 2 3 4 5 6 7 |
from string import Template my_template = Template('My Name is $x') print (my_template.substitute({'x' : "saima"})) |
- First of all import Template class from string module.
- Then create a template that has placeholder for value of x.
- And finally Substitute value of x in above template.
So this way we implement template in python, and now see the result.
You can see x is replaced into saima.
Data Output Program For Template
Let’s make a simple data output program. It will output all the items in a user’s e-cart.
- We will create template for that output then fill it with cart information.
- So open your python IDE and create a python file.
- Now write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from string import Template def Main(): cart = [] # create a list # add items into list cart.append(dict(item="Books", price=90, qty=5)) cart.append(dict(item="Mobile", price=100, qty=40)) cart.append(dict(item="Laptop", price=900, qty=2)) cart.append(dict(item="Tables", price=50, qty=10)) # create template cart_template = Template("$qty x $item = $price") total = 0 print("My Cart :") for cart_data in cart: print(cart_template.substitute(cart_data)) total += cart_data["price"] print("Toal Price : " + str(total)) if __name__ == '__main__': Main() |
- Define a main function.
- Inside this function create a list and insert some items into the list.
- Then create a template.
- Create a temporary variable to keep the total price.
- And start a for loop for depicting data from the cart and then substitute the template.
- Lastly call the Main() function.
So now let’s see the result –
Template Errors
Now we will see about template errors. Template Errors have two types –
- Key Error – In a Key error, the template was not given a value for a placeholder. It means No Placeholder Match.
- Value Error – In a Value error, the placeholder started with an invalid character(usually a number). It means Bad Placeholder.
Handling Template Errors
- For handling these errors, template provide a safe_subsitute() method and still give us back a string.
- safe_subsitute() method will leave placeholders unchanged if data is missing,
- You also get the placeholders in the returned string if there is an error with it.
- For example
123Template("$name had $money")
So the output of this will be – Marry had $money.
Custom Delimiters
- You can also set a custom delimiter for the placeholder variables by overriding the Template class.
- Let’s change our delimiter to the Hash symbol(#).
- And now we will edit our previous example i.e., data output program.
- Here we will use # rather than $.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
from string import Template # override the Template class class MyTemplate(Template): delimiter = "#" def Main(): cart = [] cart.append(dict(item="Books", price=90, qty=5)) cart.append(dict(item="Mobile", price=100, qty=40)) cart.append(dict(item="Laptop", price=900, qty=2)) cart.append(dict(item="Tables", price=50, qty=10)) # call the subclass of template # this will substitute the value using # delimiter cart_template = MyTemplate("#qty x #item = #price") total = 0 print("My Cart :") for cart_data in cart: print(cart_template.substitute(cart_data)) total += cart_data["price"] print("Toal Price : " + str(total)) if __name__ == '__main__': Main() |
- First of all create a subclass and override the base class.
- Declare a delimiter, the delimiter should be #.
- And then change the template, now in template we will use # instead of $.
- So let’s see what is the result of using custom delimiters.
We get the same output as we had get in $- based substitution.
So you don’t have to use $ sign, but it is default. If you gonna be use some other sign then # is pretty common used these days, even using the % sign is pretty common.
Why Use Custom Templates ?
So now the question is that – why use custom templates. So answer is below –
- It saves typing and reduces code size.
- Easy to implement custom templates from command line.
- For eg. – MyPhoto_$n$ext = MyPhoto_0.jpg, MyPhoto_1.jpg etc.
- Custom templates are extremely useful for webpages, as a webpage generally always follows the same template but with different data.
Some extra Information about Template
Till now we have seen a lot of information about templates and now we will discuss about some extra but more useful informations. So let’s see, what they are.
- If you need to use character that is your delimiter, you can escape it with two repeating delimiters. For eg. – ” I have $$20″ the output would be I have $20.
- Also when creating a subclass you can also override the Regular Expression for the template. The variable idpattern is set to the expression : “[_a-z][_a-z0-9]*“ by default.
- To attach a string to the end of your placeholder, you need to specify the placeholder name in {} brackets.
- For eg. – Template(“It is an open ${place}yard”) with the value “court” , then the output would be – It is an open courtyard.
Recommended articles :
- Python Split String By Character – Split String Using split() method
- Python Sort Dictionary By Value – Sort With Lambda Function And Operator Module
- Linear Search Python – Learn Linear Search With Example
- Data Backup Methods That Can Work for Your Business
- Python NumPy Tutorial – Getting Started With NumPy
So this was all about the Python Template Class Tutorial For Beginners. I hope you have learned lot of things about template. So if you found it helpful then please share with others. And if you have any query regarding this then submit your queries in comment box. Thanks