Templates – NextGen Markup pt.1

I got the idea for this series of articles after looking a bit deeper at the web components introduction working draft. Pretty soon I realized that the proposed component model gives us more power over our markup and introduce concepts that up to now where available only to programming languages.

This series of guides will make a brief introduction on the 4 key pieces of web components: Templates, Decorators, Custom Elements and Shadow DOM. Keep in mind that we are talking about an editors draft, and it is in no way supported by the browsers yet. I will try to explain what it is about, offer an example and explain the base functionality of each piece. Starting with Templates.

Templates

So, what are templates? Well, according to W3C, templates are

a method for declaring inert DOM subtrees in HTML and manipulating them to instantiate document fragments with identical contents.

Practically, in modern web apps we often have the need to use the same subtree of nodes multiple times, fill it with our content and append it to the tree. For example, you retrieve a list of articles from the database, and you want to append multple li tags in your document, one for each article. And of course, each li includes more nodes, like a link, an image, a paragraph etc. Until now, HTML didn’t provide a native way of doing that. So developers came up with a couple of solutions.

Hidden elements

This was the simplest solution and the most inefficient. Just put your markup somewhere in the DOM, hide it (usually with display:none) and when needed, clone it, fill it with your data and push it back in the DOM. Of course, this had a number of disadvantages. For one, all the resources were loaded. If you had an image in there, the browser would fetch it. If you had a script, the browser would execute it. Also, the overall performance was affected for no reason. Traversal through the DOM had more nodes to go through. Selectors were slower, as well as rendering.

String templates

If I am not wrong, this was made popular by John Resig back in 2008. Practically you define your templates as strings inside a script tag. This eliminates all the disadvantages of the previous method, but it does push towards run time parsing via innerHTML which might leave you open to XSS attacks. Also, in my view it’s not semantic, since we are talking about templates and not strings.

Defining a template

Definition of a template is really easy. Just use a <template> tag and put all your code inside there. For demostration purposes we will assume about building a template for printing a list of cars.

<template id="carTemplate">
  <li>
    <span class="carBrand"></span>&nbsp;
    <span class="carName"></span>
  </li>
</template>

It doesn’t get any simpler than that. Keep in mind that you can have your template definition in your head or in your body, it is still valid. Like I said in the beginning, the whole subtree is inert. Meaning that it’s not actually part of the DOM. If you put there an img tag with a valid src, the browser will still not fetch the image. And if you try to select an element from the template, you will get 0 results:

document.querySelectorAll('.carBrand').length; // length is 0

If you take a look at the DOM Inspector, we can notice that the template contents are actually a DocumentFragment:
document-fragment
So, how do we manipulate, how do we use the template? Well the element itself has the property content, which you manipulate as if it was its own DOM. Here is an example:

var template = document.getElementById('carTemplate');
template.content.querySelector(".carBrand").length; // length is 1

And to finally make the template “go live” what we need is to clone its contents and append them to the DOM. Here is an example:

var template = document.getElementById('carTemplate');
var car = template.content.cloneNode(true);
car.querySelector(".carBrand").innerHTML = "SEAT";
car.querySelector(".carName").innerHTML = "IBIZA";

document.getElementById("carList").appendChild(car);

Practically, the way of working is the same as with string templates. However, this is more standardized and we are using the tags for the job they are built for.

Here is a pen with a working example of templates, based on what has been discussed here.

Web components are still an editors draft. The spec will probably go through a lot of changes in the future. Also keep in mind that browser support is very poor at the moment. Latest version of Chrome seems to support a good subset of the features defined, but the biggest support comes with Chrome Canary.

Interested in Web Components? How about reading the next article in the series? Find out more about Decorators

24 Responses to Templates – NextGen Markup pt.1
  1. [...] Not sure what this is about? Have you read the first part? [...]... prevent-default.com/decorators-nextgen-markup-pt-2
  2. [...] sure what this is about? Have you read the first and second [...]... prevent-default.com/custom-elements-nextgen-markup-pt-3
  3. [...] http://www.prevent-default.com/templates-nextgen-markup-pt-1 [...]... briantree.se/gettin-modular-web-components
  4. [...] http://www.prevent-default.com/templates-nextgen-markup-pt-1 [...]... briantree.se/gettin-modular-web-components
  5. Http://Audioboo.Fm/Clover86Bill Reply

    Admiring the persistence you put into your website and detailed
    information you provide. It’s nice to come across a blog every once in a while that
    isn’t the same outdated rehashed information.
    Excellent read! I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

  6. clash of clans pirata Reply

    Before you know about your target audience. That is why they are interesting and
    fascinating players to clash of clans pirata engage more
    diverse than ever. Some mobile games, puzzle, racing,
    sports, online shopping, visit and register yourself with Bingo MagiX.
    It’s very curious to see someone glued to his interest.
    There was a grand hit.

  7. migliore mirrorless Reply

    Remarkable! Its genuinely amazing piece of writing, I have got much clear idea concerning from this paragraph.

  8. top grills in 2015 Reply

    magnificent issues altogether, you simply won a new reader.
    What could you recommend about your post that you made a few days in the past?
    Any positive?

  9. best skis compared Reply

    you’re really a good webmaster. The website loading speed is incredible.
    It seems that you’re doing any distinctive trick. In addition, The contents
    are masterwork. you have done a fantastic activity in this matter!

  10. meilleur tv led 2015 Reply

    What’s up to all, for the reason that I am actually keen of reading
    this webpage’s post to be updated daily. It contains good information.

  11. Edna Reply

    Most common capacities are 5000 litres, 10000 litres, and 20000 litres.
    There is considerable expense involved with installing a septic
    tank. In fact, there would be plenty of surplus water to irrigate
    the garden or sell to other consumers.

  12. Calvin Reply

    The entire effect of these rugs to a room should be considered when purchasing
    one. Most of the time, when the topic is all about wastewater
    and sewage, the image people often get is that of bad smells and all that grime.
    In fact, there would be plenty of surplus water to irrigate
    the garden or sell to other consumers.

  13. Lucie Reply

    I think the admin of this web site is actually working hard
    in support of his web site, since here every information is
    quality based stuff.

  14. Sunny Reply

    We had better use Msconfig or ask help from Windows optimization. Pipes and fittings are often made of
    the same base material such as copper, steel, polyvinyl chloride (PVC), and chlorinated polyvinyl
    chloride (CPVC). It is not known what prompted officials to drain that specific septic tank looking for Noah’s body.

  15. aspiratoare fara sac preturi Reply

    If you wish for to grow your familiarity only keep visiting this site and be updated
    with the most up-to-date information posted here.

  16. Tyson Reply

    Every sports person whether he is a man or women needs sports supplements
    in order to avail best results. Before we can start talking about diet pills that actually work,
    we need to establish the criteria to judge them by.
    As after the tiring workouts session the body of bodybuilder is malnourished then the requirements of post workout supplements
    increases.

  17. Peggy Reply

    “The old saying used to be diagnosed and adios, and now that spectrum has completely changed. Before we can start talking about diet pills that actually work, we need to establish the criteria to judge them by. Do a simple search on Google or Amazon for a keyword like “dog supplements” and instantly you will get hundreds of thousands of results.

  18. Williams Reply

    The fact is that nowadays there are hundreds if not thousands of different
    types of dog supplements and treats that you
    can buy today. Sometimes eating of bad calories result in making the dieter overweight which is really a matter
    of concern because it directly targets the working efficiency of its user.
    As after the tiring workouts session the body of bodybuilder is malnourished
    then the requirements of post workout supplements increases.

  19. Jamal Reply

    Here at Createch we have made a variety of supplements, several of which
    are intended to do an exact job with your body. In fact
    the height of a teenager increases dramatically.
    Do a simple search on Google or Amazon for a keyword
    like “dog supplements” and instantly you will get hundreds of thousands of results.

  20. Tarah Reply

    Most of those supplements work by stopping the cause of baldness.
    Its member companies manufacture popular national brands as
    well as the store brands marketed by major supermarkets, drug stores and discount chains.
    You may think that purchasing vegetables at a farmers
    market is healthier but you must be sure they use organic farming methods otherwise you may as well go to the local
    supermarket.

  21. national craigslist search Reply

    With Pay – Pal, it is possible to sell on its affiliated auction site e – Bay, in addition to selling via your own personal website.

    Type your e-mail address into your email text boxes and after
    that type a description of your respective pertinent skills,
    the service you are able to provide as well as your job
    needs in to the “Description” text box. List your animal’s age, physical characteristics,
    vaccinations and specifics of his temperament. When posting an ad to your classifieds website, it can be a good idea to feature photos
    whenever possible. This will allow that you access the ad anytime devoid of to
    scroll through multiple postings. national craigslist search Type your e-mail address into your email
    text boxes and after that type a description of your respective pertinent skills, the service you are able
    to provide as well as your job needs in to the “Description” text box.
    List your animal’s age, physical characteristics, vaccinations and specifics of his temperament.

    When posting an ad to your classifieds website, it can be
    a good idea to feature photos whenever possible. This will allow that you access the ad anytime devoid
    of to scroll through multiple postings.

  22. yahoo dog breeds Reply

    These types of medications behave as antistimulants for your
    canine, keeping the neurons inside the brain quiet without making your canine appear
    drugged.

    Ammonia is a smell that dogs are not fond of, as outlined by Gardening Know How.
    Many dogs will not develop symptoms from this yeast.
    Bitter Orange is often placed on such things as furniture legs to
    stop a puppy from chewing with them, or bandages to prevent a wounded dog from licking
    or nibbling at them. Instead, play which has a soft toy which will help
    prevent if your dog becomes too aggressive. yahoo dog breeds Ammonia
    is a smell that dogs are not fond of, as outlined by Gardening Know How.
    Many dogs will not develop symptoms from this yeast.

    Bitter Orange is often placed on such things as furniture legs to stop a
    puppy from chewing with them, or bandages to prevent a wounded dog from licking or nibbling at them.
    Instead, play which has a soft toy which will help prevent if your dog becomes too aggressive.

  23. Ryret 6 Polluver Long Sleeve Couples Sport Hoodies Reply

    A lot of whatever you state is astonishingly legitimate and that makes me wonder why I hadn’t looked at this in this light before. This particular piece truly did switch the light on for me personally as far as this specific issue goes. Nevertheless there is actually just one position I am not necessarily too cozy with so while I try to reconcile that with the actual central idea of your position, allow me see exactly what the rest of the visitors have to point out.Well done.

  24. AbbeyFLiukko Reply

    Hello, yeah this piece of writing is in fact pleasant and I have learned lot of things from
    it on the topic of blogging. thanks.

    my homepage AbbeyFLiukko

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>