I'm trying to come up with a purely front-end solution to a common practice.
In the past, I've stored the HTML for reused website elements (like the <nav>, <header>, <footer>, etc.) in a functions.php file, and used php functions to call these things in on multiple pages. This of course makes it easier to make changes site-wide, making my life easier.
However, I don't really want to use PHP (or in the past, ASP) to do this anymore. Does any one know of a clean way to do this in Javascript, jQuery or even Node? To be clear I want to call a function in the HTML (like writeNav(); ) that pulls the HTML for the nav. I'd rather not include <script> tags everywhere, if possible.
One very common solution for "building up a library of chunks of HTML that can be reused elsewhere" is "templating". There are numerous templating libraries to choose from (Underscore even has its own, small, template function), but I'd recommend looking at Handlebars.js first, as it's very robust but also very simple.
Handlebars templates will allow you to store your HTML however you want:
in strings in your .js files,
in <script type='text/handlebars'> tags on your html pages, or
in separate html files that get compiled in to a single JS file
It will also allow you to swap out small pieces of the HTML, so that you could (for instance) have a header that gets used all over, but replaces the title, like so:
<h3>{{title}}</h3>
The Handlebars site (http://handlebarsjs.com/) has an excellent run through; I highly recommend it.
There are also text editors like BBEdit with include support if it's just about organizing how you write your HTML.
I think what you're talking about are html includes.
This is not really a production worthy solution, but gets me through the prototyping phase.
Using jQuery, include this in your $(document).ready() callback:
$(".include").each(function() {
var inc = $(this);
$.ajax({
url : inc.attr("title"),
dataType : 'html',
success : function(data) {
inc.replaceWith(data);
console.log("adding " + inc.attr("title"));
});
Then in the body wherever you want to include an html file, do this:
<div class="include" title="path/to/html/file.html"></div>
All elements (divs, spans, etc) with the "include" attribute will be replaced by the content of the file path in the title attribute.
Note: the entire tag will be replaced in this process.
This is trivial with jQuery, e.g.
function writeP(str){
document.write($('<p />').text(str).get(0));
}
You could then do something like:
<div class="foo">
<script type="text/javascript">writeP('hello');</script>
</div>
...which would result in:
<div class="foo">
<p>hello</p>
</div>
That example is silly, but I believe the mechanism is in the spirit of what it is you're trying to accomplish.
Cheers
Related
I need to insert a large amount of HTML into the DOM.
My current way of doing this is copy-pasting the HTML I need to insert into a JS file, formatting it such that it's bug-free within the string, and then using insertAdjacentHTML() to insert.
Having a huge, multi-line string of copy-pasted HTML in the JS just feels dirty every time I happen to scroll through it.
The only constraint is that I really want to avoid using libraries if I can.
Better in this case is pretty much a secure implementation that's an improvement in readability.
Even if you don't wish to use a HTML templating tool, you can still include the HTML in a similar manner.
The handlebars.js site includes some examples, such as including the HTML in the .html file itself, selecting the element, and parsing its contents:
You can deliver a template to the browser by including it in a tag.
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
Compile a template in JavaScript by using Handlebars.compile
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
In your case, you could replace the type property in the html to anything obvious, and retrieve the contents by calling document.querySelector("htmlString").innerHTML.
Other options include loading the HTML as a separate file via AJAX, or if you're daring, writing your own transpiler to stick the HTML in the Javascript for you (which is basically what React does with JSX)
One last thing to consider: you will want to ensure that the injected HTML doesn't include any potential XSS vulnerabilities or that any DOM events won't get screwed up as a result of adding the HTML (though using insertAdjacentHTML should prevent events from breaking).
Also, consider looking over this HTML injection code I wrote awhile back to ensure you're avoiding (some but not all) possible pitfalls:
https://github.com/jsweeneydev/HTMLTemplate/blob/master/htmltemplate.js
Good luck!
I'm pretty new to web development. What is the best practice in keeping the same sidebar and other elements across web pages on one's site? Do you store the sidebar html and call that? If so, how would one go about doing something like that?
There're many options to handle this problem but I've found easy one using jQuery. Use this if it suits your requirements.
Add the jQuery CDN in your HTML file.
Create a JS file as sidebar.js.
Copy all your HTML code of the sidebar and store as a string variable in a function of the JS file. as
function loadNavbarDiv() {
String navbar_code_str = '<nav><div>...</div></nav>
$('body').append(navbar_code_str);
}
Then in the HTML file, you want to add navigation bar, add folowing code in your <head>
<script src="sidebar.js"></script>
<script>
$(document).ready(function(){
loadNavDiv();
});
</script>
It's working fine for me.
Happy coding!
Here's one way to do it: use "include" files. No JavaScript required. The server does the work, instead of requiring the client to add the content.
SSI, or Server Side Includes, were first developed to allow Web
developers to "include" HTML documents inside other pages. If your Web
server supports SSI, it's easy to create templates for your Web site.
Save the HTML for the common elements of your site as separate files.
For example, your navigation section might be saved as navigation.html
or navigation.ssi.
Use the following SSI tag to include that HTML in each page.
<!--#include virtual="path to file/include-file.html" -->
Use that same code on every page that you want to include the file.
That page also describes some other approaches. But if you know this is called using include files, you can search for it more easily. For example, this article describes includes and how to call them from JavaScript if you must.
As long as you're only coding in html, you will need to copy your html into every page. You can store the css for the sidebar in one and the same file and call that on every page though.
Other scripting languages and frameworks might contain templates (php) or master pages (asp.net) for example which make it possible to use the same code in different pages.
I'm using require.js and text.js to load a template file that has a bunch of <script> templates in it:
e.g. /scripts/templates/comments.html
<script type="text/template" id="js-comment-reply-tmpl">
// html in here
</script>
<script type="text/template" id="js-comment-edit-tmpl">
// html in here
</script>
And because using underscore's template system (or any similar js micro-templating system), this file itself gets loaded as a string. Is there a smart way to just grab each template from within that file? e.g. $(template).html() wrap it in jQuery and then do a find() or something on it? I'd essentially have to place it into the DOM first though, so that would probably be slow as hell and I might as well just not even load it with text.js and just pluck it out of the DOM initially.
My other thought is to split them each into their own files, but then that would slow down on request time (although I'd probably just end up using r.js with node to minify this all in the end anyway so it wouldn't matter).
e.g. /scripts/templates/comment_reply.html
<script type="text/template" id="js-comment-reply-tmpl">
// html in here
</script>
e.g. /scripts/templates/comment_edit.html
// html in here
What's the best/most efficient way to do this?
I would advise moving each template into it's own file and loading them all separately. Some of the advantages of doing so are:
Easier maintainance - Searching for a template in a project is easier if they all have their own names and it also reduces hassle with source control conflicts if developers aren't all editing the same file.
Portability - If you end up using a templating system that can be used on the server (like Mustache) then the templates are already easy to share between front and back-end.
The main disadvantage that you already highlighted are the extra requests, but you should definitely not be going to production without building your scripts with r.js so this shouldn't be a problem
Update: after another day of digging
into this issue, I have found that the
current jQuery template lib provides
no way to do this. this article
describes a good approach.
I would still like to hear of any
additional thoughts on doing this. The
article linked above requires that the
returned string of templates be
inserted into the DOM. Seems as though
leaving the DOM out of this would be
ideal, and less overhead on the
browser. Imagine a large page, with
multiple composite templates that may
not get used. Although, maybe because
the templates are wrapped in a script
tag, there is only a single DOM item per template? Come on, let's
hear some thoughts...
Using jQuery template libs, what's the best way to combine multiple, related, relatively small templates together? Do you need a single <script> tag for each individual template? What about in the case of dynamically pulling these templates via AJAX? Can I combine these templates somehow?
Consider the following:
<script id="movieTemplate" type="text/x-jquery-tmpl">
{{tmpl "#titleTemplate"}}
<tr class="detail"><td>Director: ${Director}</td></tr>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<tr class="title"><td>${Name}</td></tr>
</script>
Now because these two templates are very closely related (and one depends on the other) it would make sense to consolidate these into a single AJAX call, and get them both at once. I have a few ideas, but I'd like to know if there is common/best way to do this? Currently I pull in a chunk of HTML, and then do a .find() to get the specific peice of HTML for a template... e.g.:
var templatePackage = fancyAjaxCalltoGetTemplates();
"templatePackage" might then look like this:
<div id="templatePkg">
<div id="movieTemplate">
{{tmpl "#titleTemplate"}}
<tr class="detail"><td>Director: ${Director}</td></tr>
</div>
<div id="titleTemplate">
<tr class="title"><td>${Name}</td></tr>
</div>
</div>
I could then do:
var titleTemplate = jQuery.template('titleTemplate', $(templatePackage).find('#titleTemplate') );
and
var movieTemplate = jQuery.template('movieTemplate', $(templatePackage).find('#movieTemplate') );
...let me know what you think... what would you do?
I like the referenced article in your update, except the assumption that you can't cache templates unless you insert them into the DOM. From the jQuery.tmpl documentation,
"To cache the template when using markup that is obtained from a string (rather than from inline markup in the page), use $.template( name, markup ) to create a named template for reuse. See jQuery.template()."
Using this, we can build a javascript template management system that allows us to load as many templates at a time as we need while keeping the DOM clean. On the client, keep a hash of template objects by name. You can use your favorite object based javascript pattern here, but I would think the structure could be like this:
templates[templateName] = {
templateMarkup: markupFromServer,
loadedAt: Date.now(),
compiledTemplateFunction: jQuery.template( templateName, markupFromServer )
}
Then use the templates to generate HTML like this:
templates['unique-name'].compiledTemplateFunction(inputData)
Then, build an unload mechanism to free up memory:
function unload(templateName) {
delete templates[templateName];
delete jquery.template[templateName];
}
Most importantly, you now have a method of storing multiple templates so you can make requests like: $.get('/TemplateManagement/Render', arrayOfTemplateNamesToLoad, loadManyTemplatesSuccess) to load multiple templates at a time. The only thing we need is a controller TemplateManagement that will take an array of template names as an input and return JSON that pairs a template name with its markup. There are a few ways to do this but it seems to me the most convenient is to define partial views for each template. In ASP.NET MVC 3, you can use this technique and RenderPartial to emit each template's markup into a JSON response. You can either name the partial views the same as the templates or map the names in some custom way.
OK, I read the article you reference in this post. As I see it, his way is probably one of the best ways to load up the template page(s). The only thing I don't like is the asynchronous problems that could crop up, esp. if you need to immediately do some templating before the async get returns... plus any binding issues that could happen before it returns something. In several projects I have done I use his "ancient" SSI (server side includes), but I just use something even easier like:
<% Response.WriteFile("this_page_template_file.html"); %>
You could put it anywhere where you'd place a tag. Like he says, just put in only the templates you need, or maybe include two templates: one is a "base" template with commonly-used items and the second one would have the page-specific ones with template references {{tmpl}}.
Is this even close to an answer? ;-)
[First off, great question. I love this topic]
I have no experience with the plugin "jquery-template-libs", but there is a particular lightweight javascript template plugins that are becoming almost a standard and plays very nicely with jQuery, which is probably better suited for the task than JTL, Mustache:
https://github.com/janl/mustache.js
It's got something that's called a "partial" which is essentially a way to include smaller templates within another one. Which sounds like it will help you out a lot.
On top of that there is a library called ICanHaz.js:
http://icanhazjs.com/
ICanHaz essentially extends Mustache to include built in functionality for templates and works incredibly well.
Mustache/ICanHaz allow you to add templates by variable, by a json call or by using tags. The choice is yours.
I know this is an old question but you might want to take a look at Closure-Templates. They provide the kind of functionality you're after with the added advantage of being compiled into JavaScript at compile-time instead of at run-time in each user's browser.
If you do decide to look into using them then I'd suggest using plovr for building them.
There are essentially 2 places to define JavaScript functions in Grails, directly in a element on the GSP, and within a separate javascript source file under /web-app/js (for example, application.js). We have defined a commonly reused javascript function within application.js, but we also need to be able to generate parts of the function dynamically using groovy code. Unfortunately, ${some groovy code} does not appear to be processed within separate javascript source files.
Is the only way to do this by defining the javascript function within a script tag on a GSP page, or is there a more general solution? Obviously we could define the javascript function in a script tag within a template GSP file which would be reused, but there is a lot of push to keep our javascript functions defined all together in one place (i.e. the external javascript source file). This has performance benefits as well (the javascript source files are usually just downloaded once by each client's browser, instead of reloading the same javascript functions within the source of every html page they visit). I have toyed around with the idea of breaking the function up into static and dynamic pieces, putting the static ones in the external source and putting the dynamic ones in the template GSP, then gluing them together, but this seems like an unnecessary hack.
Any ideas?
(edit: It may sound like the idea of dynamically generating parts of a JavaScript function, which is then downloaded once and used over and over again by the client, would be a bad idea. However, the piece which is "dynamic" only changes perhaps once a week or month, and then only very slightly. Mostly we just want this piece generated off the database, even if only once, instead of hard coded.)
An easy solution to keep your JavaScript unobtrusive is to create a JavaScriptController and map its actions "/js/*" by adding this to your UrlMappings.groovy file:
"/js/$action"{
controller = "javascript"
}
then just create an action for each dynamic JS file you want, include in in your layout <HEAD>, and presto, you've got a JS file that you can insert Grails snippets into! :)
Note: I've found that there's currently a bug in Grails that doesn't map file extensions to content-types properly, so you'll need to include <%# page contentType="text/javascript; UTF-8" %> at the top of your view files.
This is a great solution. I would like to offer a suggestion to use somthing other then a mapping of "/js/$action" because this is no longer going to allow you to access you javascript files in /web-app/js/. All your javascript files would have to be moved to a the directory your controller would point to.
I would use something like
"/dynjs/$action"
This way you still can point to files in the /web-app/js/ files with out conflict and enjoy the benifits of gsp tags in javascript files
Please correct me if I'm wrong.
Or this... have a tag/service/dynamic method that lets tags write out their JS+CSS+whatever else, to a "cache" which is used to build the JS+CSS resources by a different controller.
Full concept here: [http://www.anyware.co.uk/2005/2009/01/19/an-idea-to-give-grails-tags-esp/][1]
If you want to use models created by the controller (that rendered HTML page which reference the Javascript in which you intend to use groovy code) in the Javascript code, then you can use this technique:
This technique does not need to change URL mappings and does not require you to create extra controller.
In your view GSP add javascript as follows:
<script type="text/javascript">
<g:render template="/javascript/yourJavascriptFile"/>
</script>
In views folder create a "javascript" folder. And create a file named:
_yourJavascriptFile.gsp
You can not only use all the GSP code in your _yourJavascriptFile.gsp file, but you can also use all the models created in your controller (that is rendering the view).
NOTE: There is nothing special about javascript folder. You can name it anything you want OR use an existing view folder. This is just a matter of organizing and identifying your HTML spitting GSP from Javascript spitting GSPs. Alternatively, you can use some naming conventions like: _something.js.gsp etc.
Name your scripts like this
/wherever/the/js/files/are/thescript.js.gsp
The gsp code inside will be rendered correctly by grails. This works, but I have no idea if it's considered a Good Idea or not.
There is another way - pass in the generated code into a function that expects closures. Those closures is generated by the program of course. The generated code is of course inlined/script-tagged in the gsp page.
it may or may not work depending on the nature of the code being generated. But i suspect it will work, and if it doesnt, minor tweaking to the coding style of your javascript will definitely make it work. Though, if these 'generated' code doesnt change much, this quite overkill imo.