How do I split html from javascript when rendering new content? - javascript

One thing I don't like about writing javascript-based applications is that you have to put a lot of HTML code in Javascript to render new content. Is there a way I can split this up? I find it messy and bloated to combine them in the same javascript code.

You should check out jQuery's Template plugin, it might be helpful depending on what your creating.

May be I cannot understand the question but you can put javascript in the separate file:
<script type="text/javascript" src="some.js"></script>
And you can use jQuery which gives you another abstraction level under HTML:
$('div.button').animate({left: 650, height: 38}, 'slow');

Have you tried a client side template system like EJS ?

I often use a hidden div with prepared HTML which serves like a sample. Then in JS I just take a copy of this HTML-piece and insert the dynamic values.
IMHO, it's convenient because all samples are stored together inside HTML file, and JS code doesn't have to know much about it's structure.

Related

Is there that I can continue my HTML code in another page, while being in the main code?

Is there that I can continue my HTML code in another page, while being in the main code?
For example, in HTML you can make 1000 extra pages of JS and just use something like
<script src="js/example.js"></script>
to make the HTML page look cleaner, and less obstructed by the extra JS code,
is there a way I can do that to continue adding more HTML elements to another page while using the same stuff from my main page?
im writing a lot of HTML and don't want to make the main page too messy
If you rename your file to filename.php, you can use an include function. The code should look like this:
<?php
include 'header.html';
?>
You should probably put the files on the body. Just a warning: PHP is hard to learn at first, especially because you have to host a server and do many other things. To learn more about the subject, visit these sites:
W3schools PHP tutorial
XXAMP
Use jQuery .load()
$('#idofDiv').load('file.html');
You could consider using .php and using php include.

How to embed javascript file content into html page in Thymeleaf?

I need to embed javascript directly into html page generated by Thymeleaf
Something like:
<script th:include="../static/assets/generated/scripts.js"></script>
But this simple usage leads to SAXParseException...
Is there any easy way to switch off parsing of the th:included
content? Or any other way how to embed content of resource int the result page?
I don't think that is possible out of the box. You could probably write an extension that can do it. Or maybe there is an existing one, but I couldn't find one right now.
Does it have to to be a separate JavaScript file? Can't you put your JavaScript code into a fragment and include it like any other fragment?
NB: Including JavaScript into your HTML file like that is usually bad web design und may be a sign that you have bigger problems and you haven't structured your code well. Why do you think you need to do that? Why can't you refer to an external script file?
Thats not a Thymeleaf-Thing. It's classic html:
<script src="/assets/generated/scripts.js"></script>
In version 3.0, you can do it in this way
<script th:src="#{/webjars/jquery/dist/jquery.min.js}"></script>

Comparmentalize HTML via Javascript or jQuery

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

Best way to package multiple jQuery templates in single xHttpRequest?

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.

Using an HTML snippet for a template in JavaScript (jQuery)

I currently am working on a little app that requests user info from my server and displays them using a special template.
At first, I just hardcoded the little snippet in jQuery:
$("<li><div class='outer'><table><tr><td rowspan=2 class='imgcontainer'><img class='thumb'/></td><td><span class='username'/></td></tr><tr><td><span class='name'/></td></tr></table></div></li>")
I clone it several times.
It's ugly and I want it to have syntax highlighting and whatnot, so it would be better for me to have it in the HTML file itself.
Also, it will make merges easier so somebody can just change a line or two.
Is there a pattern for this? Am I OK putting it in the HTML file that I include this JS in (there's only one), and making it hidden using CSS.
The third option I thought of is just creating a separate HTML file and having jQuery request that from the server to keep it separate. Is this technique used much?
Also, is there any term I can use to describe what I'm doing? (It's harder to ask a question for a concept I don't know the name for)
I gave a similar answer on SO earlier today. What you are looking for is called micro-templates. John Resig posted this on his blog. Essentially you can get a json dataset and apply a template to the data to create html and update the DOM.

Categories