views:

77

answers:

3

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.

+1  A: 

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.

Matthew Flaschen
+1  A: 

It depends on your environment. HTML is (in a simple environ) often included with a server-side include (the syntax of which will depend on your server).

That way you could have:

<!-- #include header.html -->
<h1>Blog Page</h1>
<p>content...</p>
<!-- #include footer.html -->

Javascript is included externally so can be called from anywhere. If you're in a "simple" environment (no server-side code, CMS, etc) you might call module.js which in turn loads specific CSS styles and injects into the DOM the HTML you require.

If you're using a CMS of any sort, they will often have a module idea or plug-ins that wrap this up for you. What are you working with here?

Alex Mcp
Just dipping my toes in the water and doing some fact finding.
John Leonard
Then I would use the JS approach. Leave a hook in the HTML code (<div #id="replaceMe"></div>), and include the javascript file. The JS will create DOM nodes for your HTML, apply styles to them, replace your "hook" and create any JS functions you'll need to run your bit.
Alex Mcp
A: 

Generally you can put snippets into a separate file that you can add in with a server side include:

<!--#include FILE="you_snippet.html" -->

If you have the option, you might want to have a look at some template languages like Apache Velocity. In Velocity, not only can you include different files, you can define macros that will generate the html for you.

Chris J