Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable view components in HTML

Can you create reusable components in html? Let's say I want to encapsulate some css / html and js into a tidy reusable component. How do web developers do this? I'm coming from the Flex, C# side of the planet.

like image 470
JLeonard Avatar asked Apr 30 '10 20:04

JLeonard


People also ask

What is reusable component?

In React, a reusable component is a piece of UI that can be used in various parts of an application to build more than one UI instance. For instance, we can have a Button component that displays different texts on different pages.

What are the components of HTML?

An HTML element is defined by a start tag, some content, and an end tag.

Why do we need reusable components?

Having reusable common components has advantages like,Low learning curve. Consistency across the ecosystem - with re-usable components user-experience will be same across all the products. Easy to maintain the products - any issue with component found in one product would be fixed automatically for all the products.


2 Answers

2017 update

This question is 7 years old and a lot has changed since. Web components and are now implemented or can be used with polyfills in every major browser. Which means you can use Polymer by Google or X-Tag supported by Microsoft made exactly for this.

Sample approach using Polymer:

custom tag declaration in custom-tag.html:

<dom-module id="custom-tag">

    <template>

        <style>
            h1 {
               color: red;
            }               
        </style>

        <div class="text-holder">       
            <h1>[[name]]</h1>
            <p>[[description]]</p>
        </div>

    </template>

</dom-module>

<script>
    Polymer({
        is: "custom-tag",
        properties: {
            name: String,
            description: String
        }
    });
</script>

how to use custom tag in your page:

include tag in head:

<link rel="import" href="path/to/custom-tag.html"/>

and then:

<custom-tag
    name="Lorem"
    description="Lorem ipsum dolor sit amet.">
</custom-tag>

You'll need a simple http server because of the html import. Encapsulation you talked about is backed by Shadow DOM - javascript and css packed inside of custom tag won't "bleed out" and change anything outside of the element and vice versa (unless you force it). Polymer comes out with quite large asset of elements, you can find it here.

Everything about using elements and creating your own is covered here.

like image 118
cuddlecheek Avatar answered Nov 15 '22 04:11

cuddlecheek


You can use Server-Side Includes to directly import pieces of HTML (e.g. a header), but most frameworks these days tend to approach things at a higher level, e.g. Apache Taglibs or Django templates.

like image 42
Matthew Flaschen Avatar answered Nov 15 '22 03:11

Matthew Flaschen