09
-
Templates
- The term “template” is used in a number of different ways in front end web development. This is potentially confusing as the literature available using the term to mean different things at different times. The term can be used to refer to
- CSS templates. These can simply be a collection of CSS
- CMS templates. CMS templates are used to are used to enforce a common ‘look and feel’ across a website. These are often written using a mixture of CSS, php and xml.
- JavaScript templates/ templating engine. These allow easy inclusion of external data
- A templating engine, with regard to front-end development, is simply a library that binds data with markup on the fly or otherwise dynamically.
- This could occur at runtime or possibly at design time
- To add to the potential confusion the terms “template” and “framework” are also frequently used used interchangeably however they are not the same. Generally speaking framework are more powerful and have greater functionality than front-end templates.
- Software framework are abstractions in which software providing generic functionality can be selectively changed by additional user-written code . In the case of JavaScript framework the software take the form of a web application framework that makes it easier and faster to produce JavaScript that is compatible with multiple browsers and devices. Frameworks are considered in a different week of this module.
-
CSS Templates
- These are simply pre-written stylesheet without any additional logic or constrains . They are just a set of style rules which allow neat layout to be created quickly. There are many CSS template available – quality varies as does licencing but they can speed up development work considerably
-
Content Management Systems (CMS)
- Content Management Systems provide authoring, collaboration, and administration tools . They are designed to allow users with little knowledge of web programming languages or markup languages to create and manage website content. There are a huge number of systems available and sites developed using these systems make up a huge number of the sites which are currently online. Wordpress, Joomla! Drupal are three common CMS which are free to use and have non-restrictive licences
- Most CMS provide users with a
- content repository or a database to store page content, metadata, and other information assets that might be needed by the system.
- presentation layer to display content to website visitors
- based on a set of templates
- Technologies vary XSLT ; php and xml;
- Most systems use server side caching to improve performance. This works best when the site is not changed often but visits happen regularly.
- Site administration is also typically achieved through browser-based interfaces, so the system do not require users
WordPress
- WordPress has its roots as a blogging platform but its features have been extended and WordPress now powers many non-blog websites from simple multi-page brochure style sites to full-fledged social networks. It is still less powerful than other common CMS such as Joomla! or Drupal. Some examples of site built using Wordpress can be found at 🔗 https://wordpress.org/showcase/
- Word Press strengths
- user-friendly dashboard for managing content
- huge developer community with plenty of documentation and tutorials available
- thousands of themes available
- plugins and widget available to extend functionality and make it possible to create many kinds of site with WordPress
- Word Press weaknesses
- standard installation can have a lot of security issues, and is very vulnerable to attack without additional security measures
- no official support apart from user forums, you may or may not get an official response from the user forum
- less able to support sophisticated business processes such as e-commerce or multi-level users
-
Joomla!
- Joomla has been used by some very prominent companies including MTV and Harvard University. It has been used for inventory control systems, reservation systems, complex business directories as well as for the creation of basic websites. Some examples of sites created with Joomla! Can be found at 🔗 https://showcase.joomla.org/
- Joomla! strengths
- user authentication can be done with OpenID, Google, and LDAP, among others
- more than 7000 extensions
- very active user community and lots of documentation available
- Joomla! weaknesses
- back-end isn’t as user-friendly as Wordpress although it is still relatively easy to use
- there are fewer high-quality themes available when compared to some other CMS
- can be bulky and may be more than is required for simple sites
Drupal
- This is another system which is used by used by a number of high-profile companies including New York Observer, MIT and Sony Music 🔗 https://www.drupal.com/showcases
- Drupal strengths
- developed ‘hooks’ help to predict almost any issues in the system and allow developers to create custom solutions
- wide range of modules to allow user blogs, OpenID, forums, profiles, etc. to be created easily
- code modules also allow the construction and display of arbitrary data types, multiple levels and the ability to tag, organize and categorize complex content which give high levels of flexibility and functionality
- Drupal has an active and large community
- Weaknesses
- Complexity. Drupal is not for inexperienced users and customization of Drupal modules requires programming
- Drupal is hardware-intensive and performance issues can arise. This can cause expense of in terms of hosting
-
CMS templates and themes
- CMS use ‘templates’ or ‘themes’ to enforce a common look and feel across a site. Each page consists of sets of components and pages are generated dynamically when requested. The decision about which components to include on a given page and basic positioning of the components on the page is typically handled by php scripts. CSS still used for styling but layout constrained to enforce uniformity and so it can feel that you are more restricted in how a page can be styled. The exact mechanism for laying pages out varies from one CMS to another.
- Wordpress theme
- A basis theme requires a style sheet style.css and a PHP template named index.php
- Joomla template
- This consists of (at least) a PHP index file and an xml manifest file
- 📷 templateDetails.xml
- A file (in XML metadata format) used by Joomla to retrieve information about the template (name of the template, author, creation date, etc.).
- It also contains a list of the files that make up the template itself.
- The file list should include all index files, style sheets, images, media, and any other files installed with the template.
- index.php
- A file that contains the presentation code to display text, components, and modules.
- It is the central file that loads modules, parses the Joomla template data, and handles the primary display.
- Joomla then uses CSS to create the 📷 page style
- Drupal
- .info (required)
- All that is required for Drupal to see your theme is a ".info" file.
- Should the theme require them, meta data, style sheets, JavaScripts, block regions and more can be defined here.
- Everything else is optional.
- template files (.tpl.php)
- These templates are used for the (x)HTML markup and PHP variables.
xx -
JavaScript Templates
- JavaScript templates are a method of separating HTML structure from the content contained within. Templating systems generally introduce some new syntax but are quite straightforward to work with
- Real-time web apps (for example a live streaming app for event commentary), or website which require internationalisation often require that different content is displayed using the same formatting and so can benefit from separating HTML structure from the page content.
- Systems which have a lot of HTML tags included inside JavaScript strings can also benefit from using JavaScript templates. JavaScript templates are particularly useful when calling 3rd party APIs that return JSON. Asynchronous calls which return large amounts of repetitive HTML can often be refactored using JSON with client side templates and can save a great deal of cumbersome and slow string concatenation.
- JavaScript templates encourage separation of concerns which is always important when building a maintainable codebase. They can also make the development of both logic and presentation easier, improve flexibility and ease modification and maintenance.
- Templating systems work by setting up an html page structure with the variable content replaced by tokens. This is called the template. Data is held separately. The template and the data are passed through a processor which generates a document including both the page structure and the data. Different templating systems use different syntax but the general idea is that data is replaced by a symbol (double curly brackets {{ ... }} or similar ) in the template. Thus JavaScript templates are a way to separate the view (HTML structure) from the data (content).
- Implementing JavaScript Templates is basically a case of including a chosen library, fetching a template and rendering it alongside some data. Most libraries support both inline and external templates. Inline templates may be appropriate for when there are very few templates but generally templates should be external. External templates bring many benefits, chiefly that templates will not be downloaded to the client unless they are needed by the page.
- JavaScript template processing systems consist of at least
- a data model;
- one or more source templates;
- a processor or template engine;
- generated output in the form of result documents.
Data model
- This may be a relational database, a source file such as XML, an alternate format of flat file database, a spreadsheet, an external API or any other various sources of preformatted data.
- Some template processing systems are limited in the types of data that can be used.
- Others are designed for maximum flexibility and allow many different types of data.
Source template
- Source templates are traditionally specified by either:
- a pre-existing programming language;
- a specially-defined template language;
- the features of a hosting software application; or
- a hybrid combination of some or all of the above.
Template engine
- The template engine is responsible for:
- connecting to the data model
- processing the code specified in the source templates
- directing the output to a specific pipeline, text file, or stream
- some template engines also allow for additional functionality
Result documents
- These may consist of an entire html document or a document fragment
-
Contemporary Templating Engines
- Some examples of contemporary templating engines include
- jQuery templates
- Mustache
- Handlebars
jQuery templates
<body> <div id="container"></div> <script id="dataTemplate" type="text/x-jQuery-tmpl"> <p>${firstName} ${lastName}</p> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmp1.js"></script> <script type="text/javascript"> var data = [ { firstName: "Fred", lastName: "Jones"}, { firstName: "Rebecca", lastName: "Smith"}, { firstName: "joe", lastName: "Bloggs"}, { firstName: "Jim", lastName: "MacDonald"}, { firstName: "Liz", lastName: "Brown"}, { firstName: "John", lastName: "Green"} ]; //Render the data using the template $("#dataTemplate").tmpl(data).appendTo("#container"); </script> </body> </html>
- 📷 Output
- The page shown above uses both the jQuery 1.4.4 and jQuery Templates libraries. The actual template is included in a script tag with a special MIME type.
- The expression ${…} is used to display the value of a JavaScript expression within a template for example, the expression ${firstName} is used to display the value of the individual’s firstName property. You can use any JavaScript function within the ${…} expression.
- The template is rendered with the help of the tmpl() method. The following statement selects the dataTemplate and renders an array of names using the dataTemplate.
$("#dataTemplate").tmpl(data).appendTo("#container");
- The results are appended to a div element with an id of container by using the standard jQuery appendTo() method.
x -
mustache.js
- Mustache is a multi-language, logic-less templating system. The mustache.js implementation is one of many implementations and you can use mustache with a variety of programming languages.
- Mustache has a number of advantages: it has simple syntax, is small, has no dependencies and, as previously noted, is programming language agnostic.
- However the lack of built in logic and precompiled templates limits its functionality.
- Mustache.render function takes two parameters:
- the Mustache template,
- a view object that contains the data and code needed to render the template.
- Basic use replaces variables with simple strings, but it’s possible to do much more. For example it is possible to loop over an array, or make use of a special rendering function that uses the current view as its view argument.
- mustache.js is good for small projects and quick prototypes where templating complexity is at a minimum.
- A key thing to note is that you can start off a project with mustache.js and then easily upgrade to Handlebars.js later as the templates are (mostly) the same.
- Mustache example
<body> <div id="sampleArea"></div> <script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script> <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script> <script type="text/javascript"> var data = { employees: [ { firstName: "Fred", lastName: "Jones"}, { firstName: "Rebecca", lastName: "Smith"}, { firstName: "joe", lastName: "Bloggs"}, { firstName: "Jim", lastName: "MacDonald"}, { firstName: "Liz", lastName: "Brown"}, { firstName: "John", lastName: "Green"} ]}; var template = "Employees:<ul>{{#employees}}" + "<li>{{firstName}} {{lastName}}</li>" + "{{/employees}}</ul>"; var html = Mustache.to_html(template, data); $('#sampleArea').html(html); </script> </body> </html>
- 📷 Output
x -
Handlebars.js
- Handlebars.js is built on top of Mustache and (mostly) compatible with Mustache templates. Handlebars provides all of functionality Mustache does plus it also supports block expressions and precompiled templates.
- Block expressions allow more logic. A common example is advanced iterators eg. create a <ul> list iterator which wraps each item in <li>.
- Precompiled templates increase performance by a large margin in a rough performance test, precompiled Handlebars.js templates rendered in about half the time of Mustache templates
Handlebars template
- Simple template
<!doctype html> <head> <meta charset="utf-8"> <title>test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="handlebars-v4.0.11js"></script> <script src="assets/js/script4.js"></script> </head> <body> <h1>Handlebars Example</h1> <script id="basic-template" type="text/x-handlebars-template"> <table> {{#each objects}} <tr> <td>{{month}}</td> <td>{{category}}</td> <td>{{location.street.name}}</td> <td>{{outcome_status.category}}</td> </tr> {{each}} </table> </script> </body> </html>
- script4.js
$(document).ready(function(){ var req = $.ajax({ url: "https://data.police.uk/api/crimes-street/all-crime?poly=52.268,0.543:52.794,0.238:52.130,0.478&date=2017-01" dataType: "json" }); req.done(function(data) { console.log(data); var source = $("#basic-template").html(); var template = Handlebars.compile(source); var data = data; var wrapper = {objects: data}; console.log(template(wrapper)); $('body').append(template(wrapper)); }); });
- 📷 Output
x -
CSS Framework
- CSS framework are pre-prepared software framework which allow for easier, more standards-compliant web design using the Cascading Style Sheets. A CSS framework is commonly used by developers and designers as a tool to speed up the process. A CSS framework, also sometimes referred to as a front-end framework, is essentially a package that is made up of predefined HTML, CSS, and JS which can be used when starting to build out a project.. Most CSS frameworks contain at least a grid. More functional frameworks also come with more features and additional JavaScript based functions, but are mostly design oriented and unobtrusive.
- CSS frameworks are distinct from full JavaScript frameworks (AngularJS etc). Two notable and widely used examples are Bootstrap and Foundation
- CSS frameworks offer different modules and tools typically:
- reset style sheet
- grid especially for responsive web design
- web typography
- set of icons in sprites or icon fonts
- styling for tooltips, buttons, elements of forms
- parts of graphical user interfaces like accordion, tabs, slideshow or modal windows (Lightbox)
- equalizer to create equal height content
- often used CSS helper classes (left, hide)
- Bigger frameworks use pre-compiled CSS like Less or Sass.
Bootstrap
- Bootstrap is a free responsive front-end UI framework developed to facilitate faster and easier web development. It includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many other interface elements, as well as optional JavaScript plugins. Bootstrap is considered a lightweight framework but even so a page that uses Bootstrap will still require more processing to render than a standard page. Performance is therefore an important consideration when designing, developing and testing pages that use any part of the Bootstrap framework.
- Bootstrap uses compiled CSS - Bootstrap 4 uses SASS earlier versions used LESS
- 🔗 https://msdn.microsoft.com/en-us/magazine/mt147241 gives a useful overview of its advantages and disadvantages.
Foundation
- Foundation is a mobile first responsive framework built with Sass/SCSS giving designers best practices for rapid development. The framework includes most common patterns needed to rapidly prototype a responsive site.
- Foundation is open source and available on GitHub. Developers are encouraged to participate in the project and make their own contributions to the platform.
W3.CSS
- Another framework which may be worth mentioning is W3.CSS. This is another modern CSS framework with built-in responsiveness providing styling for a variety of devices: desktop, laptop, tablet, and mobile. It is small, fast and easy to learn and to use. It has good cross-browser compatibility (Chrome, Firefox, Edge, IE, Safari, Opera) and uses standard CSS only (no jQuery or JavaScript libraries required). W3.CSS is possibly more limited that other framework but is easy to learn and because it is smaller than other framework may have fewer performance issues.
-
Pre-complied stylesheets
- Stylesheets can get large, complex very quickly.
- Building functions, reusing definitions and any sort of inheritance does not happen naturally using CSS. For bigger projects, or complex systems, maintenance is a very big problem
- In order to write better CSS, the approach of separating definitions into smaller files and importing them in to one main file can be used. This goes some way towards styling components but does not solve code repetition and maintainability problems. Another approach is to apply an object oriented approach to CSS applying two or more class definition to an element. Each class adds one type of style to the element. Having multiple classes increases re-usability but decreases maintainability. Pre-processors help with organisation and can also extend CSS to allow programming constructs such as variables, nesting which can make the process of styling webpages much more efficient for programmers.
- The two most commonly used pre-processor at present are Sass and LESS. They are both very powerful CSS extensions. Basically they can be thought of as programming language designed to make CSS more maintainable, themeable, and extendable. Both Sass and LESS are backward compatible so you can easily convert your existing CSS files just by renaming the .css file extension to .less or .scss, respectively. LESS is JavaScript based and Sass is Ruby based. However there is no need for end users to know or to be aware of the programming language being used to process the files.
- While it appears that Sass is more widely used, there isn’t really a pre-processor that is better than the other. As with many decisions about programming language it basically comes down to personal preference. We will use Sass as an example to demonstrate the advantages of pre-processors.
- Pre-processed SASS file can be saved as normal CSS files for use in web sites. The most direct way to work with SAAS is to install SASS on your computer and then run the command sass input.scss output.css in a terminal window.
SAAS Syntax
- There are two syntaxes available for Sass
- SCSS (Sassy CSS) is an extension of the syntax of CSS. So every valid CSS stylesheet is a valid SCSS file with the same meaning. In addition, SCSS understands most CSS hacks and vendor-specific syntax, such as IE's old filter syntax. Basic CSS syntax is enhanced with Sass features
- Files using this syntax have the .scss extension.
- The second and older syntax, known as the indented syntax (or sometimes just "Sass") provides a more concise way of writing CSS. It uses indentation rather than brackets to indicate nesting of selectors and newlines rather than semicolons to separate properties.
Advantages of using SASS
- Sass programming constructs to be used within CSS. Some basic examples include the use of variables, nesting and partials( i.e. the ability to include external files within the CSS)
Variables
- can use variables as a way to store information that you want to reuse throughout a stylesheet. They can store things like colours, font stacks or any CSS value you think you'll want to reuse. When the Sass is processed it takes the variables defined and outputs normal CSS with the variable values placed in the CSS. This can be extremely powerful when working with brand colors and keeping them consistent throughout the site.
- Example: SCSS
$font-stack: Helvetica, sans-serif; $primary-color: #333; body { font: 100% $font-stack; color: $primary-color; }
- Generated CSS
body { font: 100% Helvetica, sans-serif; color: #333; }
Nesting
- HTML has a clear nested and visual hierarchy. CSS does not. Sass allows nesting of CSS selectors in a way that follows the same visual hierarchy as HTML. An example is when we consider some typical styles for a site's navigation: both tags and selectors can be nested. This is a good way to organize CSS and make them more readable.
- Example - SCSS
nav { ul { margin: 0; padding: 0; list-style: none; } li { display: inline-block; } a { display: block; padding: 6px 12px; text-decoration: none; } }
- generated CSS
nav ul { margin: 0; padding: 0; list-style: none; } nav li { display: inline-block; } nav a { display: block; padding: 6px 12px; text-decoration: none; }
Partials
- Partial Sass files contain snippets of CSS that can be included in other Sass files. They can be a good way to modularize CSS and help keep things easier to maintain. A partial can be identified as a Sass file named with a leading underscore e.g _partial.scss. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @import directive.
Programming constructs
- Control directives and expressions help to build similar style definitions according to matched conditions or variables. SASS supports normal if/else conditionals and loops. Loops are useful when iterating through an array or creating a series of styles as in grid widths.