I have two HTML files: One acts as a template, supplying the navigation, sidebars, etc., and the other has the main content. I'm trying to figure out how best to insert the content into the template. I need persistent URLs, so my plan was to have the content page essentially replace itself with the template, plugging the text back into the resulting page. I'm really new to front-end programming and I'm suspicious that this may be an anti-pattern, so my first question is about whether I'm barking up the right tree. The problem seems universal, and I'm sure there must be a best practice, though I haven't yet seen it discussed. If this is an acceptable way to proceed, then what JavaScript function would allow me to access the HTML of two different pages at the same time?
[EDIT: It's a small page on GitHub]
Do not do this. At current implementation HTML is not designed to be template engine. You can use HTML import but it has not full support in browsers. (compatibility table).
Usually this problem can be solved with:
Use frontend framework. Libraries like angular.js or polymer.js (and so on) usually has support of importing HTML documents in different forms.
Build your application HTML. Task runners like grunt.js usually has plugin that includes HTML.
Use server side technologies to extend your HTML from base layouts
If your application have to be consisted from different HTMLs I recommend you to try polymer. It is polyfill for web components and designed to work in such way by default.
UPD:
About edit to your question. It seems like you just need template engine for HTML. You can google for it. I use nunjucks - javascript port of python's template engine jinja2. It is lightweight, simple and can be compiled right in browser.
Another way is to use special tools for building static web pages. You have mentioned that your page is blog build from simple HTML pages. Try to use pelican. It is the static websites (blogs) generator. It is simple and fast. You can build your HTML even on your local machine and just push your HTML pages to github.
Related
Is there a method available to make maintaining the common sections in html templates (e.g. header and footer) easier?
I am trying to explore a javascript multi-page app.
In PHP, my approach for better code maintenance is to use require_once(path/to/header) and simply adjust the code in path/to/header, no need to update all pages that use the header.
Is there a similar method for that to maintain html templates? I know this can be achieved in javascript, but I was thinking of a non-dynamic method for this, for search crawlability sake. Although I have read that google can crawl javascript apps, I decided not to make the app 100% javascript generated, I want to maintain the few common sections as static html.
Anyway, what is a common approach for this scenario? Is there a compiler or something? Because right now I am thinking to build the pages in PHP and then just get the html ouput when I move the code out of development.
Any suggestions?
Search: javascript html template engines:
https://colorlib.com/wp/top-templating-engines-for-javascript/
Eg.
pug
ejs
Handlebars
I'm developing pure JS + HTML application. To keep the code clean I would like to separate my application into the several html files (i.e. ClientView.html, HistoryView.html etc). Based on user actions one or another view (or several views) would be displayed. Each view is supposed to have an underlying code in a separate JS file.
What I really want to achieve is following:
Develop view as HTML page (do not use any kind of javascript templating)
Views and viewmodels are loaded on the fly (only loaded when needed)
Some way to control dependencies.
I would be very thankful if you advice me a good start for that, as I'm quite new to modern html applications development. I myself is from WPF world, and I've been working with MVVM applications for a very long time, probably I'm wrong trying to bring same experience to javascript development.
I've found several posts about "compiling" html - (HTML "compiler" / merging application), but I don't think that it is what I need.
p.s. In my project I'm very dependent from several features from Twitter Bootsrap (first of all from grid systems)
Use a master page which contains some div to make the layout. Use JQuery to dynamically load various pages and insert into the div in the master page as required.
I want to have achieve something similar to Java Tiles framework using only client side technologies (no server side includes).
I would like to have one page, eg layout.html which will contain layout definition. Content placeholder in that page would be empty #content div tag.
I would like to have different content injected on that page based on url. Something like layout.html?content=main or layout.html?content=edit will display page with content replaced with main.html or edit.html.
The goal is to avoid duplicating code, even for layout, and to compose pages without server-side templating.
What approach would you suggest?
EDIT: I don't need a full templating library, just a way to compose a pages, similar for what tiles do.
JavaScriptMVC has a view templating system that supports different engines, including a pure JavaScript based one called EJS.
You might also want to look into Mustache especially Mustache for JavaScript.
If you would like to use jQuery, there is a decent templating engine in development as well:
http://github.com/jquery/jquery-tmpl
http://api.jquery.com/jquery.tmpl/
Check this out:
http://layout.jquery-dev.net/
I thinks it's close to what you want.
I am looking at javascriptMVC at the same time.
In the forum they are talking about using jquery layout with it.
I don't know if it fit exactly to what you want to do, but using the GWT seems to be a good approach for rich client-side applications :
You write all your application in Java with the framework, and you compile for obtain HTML and JS files working stand-alone.
Very basic question: I am coding a web app that has a handful of pages. These pages have the usual shared elements: eg, the site's header/masthead and a side-bar are present on all pages. The HTML is static (not dynamically generated, its "ajaxy-ness" is done client-side).
What is the best way of importing/"including" those common elements into my pages? The solution I am using is to have the HTML files contain empty place-holders
<div id="header"></div>
<div id="leftSideBar"></div>
(...)
and then do in jquery's $(document).ready():
$.get("header.html", function(html) { $("#header").html(html); });
// ....
Is this the best way to do this? I'm new to web development. : )
I guess I could also dig up a "macro-like" code-generation tool that I would run on the HTML files to replace, eg, "#header" with the contents of header.html. That way loading a page would require a single request for a single HTML file, which sounds better.
What is the smart way to achieve this? I am sure this problem has been solved a thousand times.
EDIT: The server-side is coded in Python+cherrypy. (I am assuming it is reasonable to try to keep away from dynamically generating HTML when doing "web 2.0-ish" web apps. Please correct me if I am wrong. As I said, I am very new to this environment.)
Thank you for your insights,
lara
If you want to include files, please consider using some backend language such as PHP or ASP. Javascript is not really meant to do this even if this would work.
<?php include 'other_file.php'; ?>
Using javascript to do this will lead, I think, to a poor SEO and the loading of the page might look weird for the end user. If you really don't want to use a backend language, some IDE have a way to handle templates, you could look into that.
Concerning frameworks, most of them have a way to handle templates. ASP.NET has the master page system, Ruby on Rails has layouts.
Here's an example using Rails :
<html>
...
<div id="content"> <%= yield %> </div>
...
</html>
Here all the content of a subpage will go into the "yield". Here's a link to learn more about that.
Some frameworks can handle multiple place holders.
To some extent, it depends on what you're using on the server side to render the pages. If your using server side scripts to generate the page you should be able to use a web framework (eg. Django or RubyOnRails) or even just a basic templating engine such as Genshi. Basic include functionality may even be built into the language you're using (ie. PHP)
If it's just static HTML you may want to look into setting up some form of server side includes such as Apache SSI or NGINX SSI. You'll need to pick the one that works with whichever server you're using, and you'll need enough access to install and configure the plugin or module.
Alternatively, you might want to look at using a script to generate your pages (edit, generate and deploy). A simple approach using cat / sed / awk / make (additional useful reference - Sed & Awk) may be all you need, or you might want to use a templating engine and a language such as Python or Perl.
I'd have the includes handled server-side, and this will mean fewer requests from the client, and may also have other benefits (easier to debug js, etc).
Having the server process includes really isn't going to put a major strain on it.
Do you localize your javascript to the page, or have a master "application.js" or similar?
If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages?
EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.
And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do.
All shared JS code lives in the SITE/javascripts directory, but it's loaded in 'tiers'
For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.
There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)
For less-shared stuff (say my library that's only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.
For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the script tag will go below the button.
For inline JS that doesn't have a target (eg: onload events) it goes at the bottom of the page.
So, how does something get into a localised library, or a site-wide library?.
The first time you need it, write it inline
The next time you need it, pull the inline code up to a localised library
If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
If it's needed from more than one region, pull it up to a site-wide library.
A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view.
However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations.
I'd recommend using features like this rather than compromising the quality/readability of the actual source code.
Yahoo!'s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he's now at Google) and he's written some interesting tools that can help you decide where to put JavaScript.
I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I'll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).
In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I've found this style works well for me, especially when doing templating on a site. I build the template engine to "autoload" my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.
Personally, I try to include several Javascript files, sorted by module (like YUI does). But once in a while, when I'm writing essentially a one-liner, I'll put it on the page.
Best practice is probably to put it on Google's servers.
(Depends what you mean by "your" javascript though I suppose :)
This is something I've been wrestling with, too. I've ended up by using my back-end PHP script to intelligently build a list of required JS files based on the content requested by the user.
By organizing my JS files into a repository that contains multiple files organized by purpose (be they general use, focused for a single page, single section, etc) I can use the chain of events that builds the page on the back-end to selectively choose which JS files get included based on need (see example below).
This is after implementing my web app without giving this aspect of the code enough thought. Now, I should also add that the javascript I use enhances but does not form the foundation of my site. If you're using something like SproutCore or Ext I imagine the solution would be somewhat different.
Here's an example for a PHP-driven website:
If your site is divided into sections and one of those sections is calendar. The user navigates to "index.phhp?module=calendar&action=view". If the PHP code is class-based the routing algorithm instantiates the CalendarModule class which is based on 'Module' and has a virtual method 'getJavascript'. This will return those javascript classes that are required to perform the action 'view' on the 'calendar' module. It can also take into account any other special requirements and return js files for those as well. The rendering code can verify that there are no duplicates of js files when the javascript include list is built for the final page. So the getJavascript method returns an array like this
return array('prototype.js','mycalendar.js');
Note that this, or some form of this, is not a new idea. But it took me some time to think it important enough to go to the trouble.
If it's only a few hundred bytes or less, and doesn't need to be used anywhere else, I would probably inline it. The network overhead for another http request will likely outweigh any performance gains that you get by pulling it out of the page.
If it needs to be used in a few places, I would put the function(s) into a common external file, and call it from an inline script as needed.
If you are targeting an iphone, try to keep anything that you want cached under 25k.
No hard and fast rules really, every approach has pros and cons, would strongly recommend you check out the articles that can be found on yahoo's developer section, so you can make informed decisions on a case by case basis.