Fondations des WC - Les templates

Dans cette article, nous allons nous intéresser aux fondations des composants web. Cela permettra de comprendre à la fois leur raison d’être et aussi comment ils sont construits.

Nous utiliserons des exemples simples et n'utiliserons pas de polyfill. Pour tester les bouts de code de cet article, le navigateur Google Chrome est le plus approprié.

Pour rappel, les spécifications des Web Components concernent :

  1. Les Templates : Permettent la réutilisation de fragments de code à l'aide de la balise <template>
  2. Le Shadow DOM : Permet l'encapsulation de sous-arbres DOM dans un élément hôte donnée.
  3. Les Custom Elements : Permettent la création et l'enregistrement de nouveaux éléments HTML
  4. Les Imports : Permettent l'importation de contenus dans un document HTML

Les Templates

Pourquoi les templates ?

Le concept de templates n'est pas nouveau, il est très utilisé par la plupart des frameworks, à la fois coté client et coté serveur.

Les templates permettent de réutiliser une partie du code sans avoir à la régénérer de manière impérative à chaque fois qu'on en a besoin.

Par exemple, une boite de dialogue est à la base une structure HTML. Au besoin, cette structure est personnalisée à l'aide de Javascript, clonée puis affichée. Voici un exemple simple de structure d'une boite de dialogue

HTML

  1. <div class="outer" style="display: none">
  2.     <div class="inner">
  3.         <div class="header"><!-- le contenu de l’entête sera injecté ici --></div>
  4.         <div class="message"><!-- le contenu du message sera injecté ici --></div>
  5.     </div>
  6. </div>

Dans cet exemple, on a utilisé l'attribut style="display:none" pour masquer la structure. Il suffit de positionner cet attribut à block pour afficher la boite de dialogue.

Javascript

  1. <script>
  2.    function afficherDialogue(type, message){
  3.       document.querySelector('.header').innerHTML = "<h3>" + type + "</h3>";
  4.       document.querySelector('.message').innerHTML = "<p>" + message + "</p>";
  5.       document.querySelector('.outer').style.display = "block";
  6.    }
  7. </script>

Avec des styles CSS, on pourrait arranger l'apparence de la boite de dialogue. Les arguments type de la fonction pourrait avoir comme valeurs possibles error, warning ou info et message le message à afficher.

D'autres approches sont possibles pour résoudre le même problème. Par exemple l'utilisation de la balise <script> pour embarquer la structure de code HTML réutilisable.

La balise <template>

La balise template permet d'embarquer une structure HTML dans une page web de sous la forme de d'un fragment DOM inerte. Cela veut dire que le contenu de la structure n'aura aucun effet sur la page, jusqu'à ce qu'on le clone et on l'insert dans la structure DOM du document.

La balise <template> apporte une approche uniforme pour la résolution de ce genre de problèmes.

Comment utiliser la balise <template> ?

Création

Il suffit de d'entourer la structure de code réutilisable par une balise <template>

HTML

  1. <div id="container"><div id="container"><!-- espace réservé pour utilisation des clones du template --></div>
  2. <template id="tmpl">
  3.     <div class="barre">
  4.            <div></div>
  5.     </div>
  6. </template>

Utilisation

Javascript

  1. // tmplContent contiendra le fragment DOM du contenu du template.
  2. var tmplContent = document.querySelector('#tmpl').content;
  3. var barre = tmplContent.querySelector( '.barre > div' );
  4. // A il suffit de personnaliser ce contenu, de le cloner et enfin l'insérer dans le DOM du document.
  5. // Ici, je vais créer 10 clones.
  6. for ( var i=0; i<10; i++) {
  7.     // Personnalisation (Il s'afit d'un fragment DOM, d'où l'utilisation de querySelector())
  8.     barre.style.height = (i * 40) + 'px';
  9.     barre.setAttribute('title', i);
  10.     // clonage  avec la méthode importNode()
  11.     var clone = document.importNode( tmplContent, true );
  12.     // Insertion dans l'arbre DOM du document
  13.     document.querySelector( '#container' ).appendChild( clone );
  14. }

Avec les styles CSS suivants :

CSS

  1. #container {
  2.         padding: 6px;
  3.         background: black;
  4.     }
  5.     #container .barre {
  6.         display: inline-block;
  7.         padding: 2px;
  8.         margin: 4px 2px;
  9.         border: 1px solid #ccc;
  10.         background: #999;
  11.     }
  12.     #container .barre > div {
  13.         width: 40px;
  14.         height: 40px;
  15.         border: 1px dashed #222;
  16.     }

On obtient :

Aperçu :

Conclusion

Au final, l'apport de la balise <template> est juste l'uniformisation de l'utilisation des fragments DOM dans un document HTML. Avant, chaque développeur utilisait sa propre méthode pour résoudre ce problème. Avec la balise <template>, le code deviendra plus cohérent et compréhensible.

Commentaires

I know this web site provides quality depending content and additional

data, is there any other site which provides such data in quality?

Check out my weblog; geek toys

whoah this weblog is great i love reading your posts.

Keep up the good work! You recognize, many people are searching round for this

info, you could help them greatly.

my web site tempo traveller from amritsar to katra

Hiya! I know this is kinda off topic nevertheless I'd figured I'd ask.

Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?

My blog goes over a lot of the same subjects as yours and I

think we could greatly benefit from each other. If you are interested feel free to shoot me an e-mail.

I look forward to hearing from you! Awesome blog by the way!

Feel free to surf to my page; Jolene

If you want to take a great deal from this paragraph then you have to apply such strategies

to your won webpage.

Here is my web page: nifty weekly option tips

Hi there very cool site!! Man .. Beautiful ..

Amazing .. I'll bookmark your site and take the feeds additionally?

I'm glad to seek out numerous helpful information right here within the put up, we'd like develop more strategies

in this regard, thanks for sharing. . . . . .

Here is my web blog - xem tên con

It's impressive that you are getting thoughts from this paragraph as well as from our argument made here.

My web site ... carshield auto warranty, www.highya.com,

Do you have a spam problem on this blog; I also am a blogger, and I

was curious about your situation; many of us have created some nice methods and we are looking to swap solutions with others, be sure to shoot me an e-mail if interested.

Feel free to visit my homepage ... nclex-rn test Prep online

Hello! Would you mind if I share your blog with my zynga group?

There's a lot of folks that I think would really enjoy your content.

Please let me know. Thanks

Here is my web-site corporate proxy Solicitation regulations

What's up colleagues, how is the whole thing, and what you want to say concerning this

article, in my view its truly remarkable in support of me.

my web site; Blogvietkieu.Com

After exploring a handful of the blog posts on your web page, I truly like your technique of blogging.

I book marked it to my bookmark webpage list and will be checking back in the

near future. Please visit my web site as well and tell me how you feel.

Here is my homepage ... Virtual Tutor

Amazing blog! Is your theme custom made or did you

download it from somewhere? A design like yours with a few

simple adjustements would really make my

blog stand out. Please let me know where you got your theme.

Many thanks

my webpage: rare earth metals market

What's up, I desire to subscribe for this weblog to get hottest updates, thus where can i

do it please help.

My blog post Blogvietkieu.Com

Thanks for finally writing about > Ajouter un commentaire

| A. Daaïf < Liked it!

Feel free to visit my blog; Corporate Proxy Solicitation Regulations

If some one wishes expert view regarding blogging and site-building after that i propose him/her to visit

this web site, Keep up the pleasant work.

My page T-Shirts

Thank you for the good writeup. It in fact used to be a enjoyment account it.

Glance complicated to far brought agreeable from you!

By the way, how can we be in contact?

Review my blog post Lara

Heya just wanted to give you a quick heads up and let you know a few of the pictures aren't loading correctly.

I'm not sure why but I think its a linking issue.

I've tried it in two different browsers and both show the same

results.

my blog post: nclex test Prep Online

Appreciating the commitment you put into your blog and in depth information you present.

It's good to come across a blog every once in a while that isn't the

same outdated rehashed material. Wonderful read! I've bookmarked your site and I'm including your RSS

feeds to my Google account.

Feel free to surf to my web site ... Option Market In India

Thank you a lot for sharing this with all people you really know what you're talking about!

Bookmarked. Kindly additionally seek advice from my

web site =). We will have a link trade arrangement among us

My web-site ... Candra

WOW just what I was looking for. Came here by searching for accepted stocks trading

Also visit my weblog :: Stock & Derivative

I am really loving the theme/design of your weblog.

Do you ever run into any internet browser compatibility issues?

A small number of my blog readers have complained about my website not working correctly in Explorer but looks great in Chrome.

Do you have any ideas to help fix this issue?

Here is my web page - broadridge proxy solicitation process

Undeniably imagine that which you stated. Your favorite reason seemed to be at the web the simplest factor to be mindful

of. I say to you, I certainly get annoyed even as other people think about issues that they just don't know about.

You controlled to hit the nail upon the highest and also defined out the entire thing with no need side effect , folks could take a signal.

Will likely be again to get more. Thanks

Look at my web-site :: proxy solicitation Jobs

Good day! I know this is kind of off topic but I was wondering if

you knew where I could find a captcha plugin for my comment form?

I'm using the same blog platform as yours and I'm having difficulty finding one?

Thanks a lot!

Also visit my webpage; Http://Blogvietkieu.com

Thanks for the marvelous posting! I definitely enjoyed reading it, you happen to be a great author.

I will be sure to bookmark your blog and will often come back

very soon. I want to encourage that you continue your great posts, have a nice holiday weekend!

Feel free to surf to my webpage ... corporate Proxy solicitation services department

Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I

acquire in fact enjoyed account your blog posts.

Any way I will be subscribing to your feeds and even I achievement you

access consistently quickly.

Feel free to surf to my web-site: corporate Proxy solicitation rules For investment

Hello, I enjoy reading through your post.

I like to write a little comment to support you.

Here is my site; Exam Season

I visited several web sites however the audio quality for audio songs existing at

this website is in fact superb.

Feel free to visit my blog post: Corporate Proxy Solicitation Services For The Underserved

I used to be recommended this blog through my cousin. I'm now not sure whether or not this post is written through him as no one

else realize such precise about my problem.

You are amazing! Thanks!

my homepage - https://biosimobi.site123.me/blog/deutsch-universal-%D0%BC%D0%B8%D0%BB%D0%BB%D0%B5%D1%80-%D1%80%D0%B5%D1%88%D0%B5%D0%B1%D0%BD%D0%B8%D0%BA">1

You ought to be a part of a contest for one of the best sites

online. I will recommend this blog!

My web page :: Corporate Proxy Solicitation Process Meaning