Front-end Series 3: Templating syntax review

  1. Template syntax families
  2. Binding simple values
  3. Binding values using Scope Blocks
  4. Grammars
  5. Parsing
  6. Consistency leads to Predictability
  7. Comparison of popular templating syntaxes
    1. String Insertion
    2. Iteration
    3. If

Templating syntax (and language syntax in general) is very interesting. How a template is written somewhat informs mental-model of how it behaves, and how the data should be structured.

The following is a syntax review of common features in front-end templating systems. This is an initial pass! If you see any errors or optimizations, please correct me in the comments and I’ll quickly correct them. Also, this isn’t a review of the (sometimes very extensive) templating engines themselves — just the template syntax.

Template syntax families

At a very high-level, template syntax falls generally into two families: element-attribute renderers, and inline-token renderers.

Element-attribute style syntax binds data, logic, and state to a template by attributes on an individual node:  <element directive="property" /> . These templates are often parsed using traditional DOM parsing techniques, looking for element attributes that match a set of defined directives for that framework.

In inline-token renderers, binding is performed by code (or expressions) in-place, using special tokens to set it apart from the markup: like  {{ , <@ , or  <% . These templates are parsed using string or pattern matching techniques on the tokens, then evaluating their contents.

These are general distinctions, and some templating frameworks use both syntax styles.

Binding simple values

Inline-token style syntax really shines when binding single values to a template:

Because the templates are parsed as strings, using pattern matching regular expressions to find tokens, the binding can occur anywhere within the template, making them very powerful:

Element-attribute syntax expressions bind simple data easily, but quickly become verbose and unwieldy when replacing complex content:

 Binding values using Scope Blocks

Many templates also include some logic expressions, such as  if, foreach, and  using. Inline-token expressions can be limited when working with logic blocks — one reason is scope management. Element-attribute syntax declares expressions on the elements themselves, which have a natural scope within the DOM tree: they start, end, and have children. This makes data binding when scope is required simple:

Inline-token expressions are parsed with pattern-matching and could occur anywhere, so the parser must maintain the scope of any logic blocks used in a template. Additionally, the template syntax must contain closing tags for each opening logic block.

Grammars

handlebars-grammarEach templating syntax comes with its own grammar — or structure. A study of language grammar is a post on its own (or a degree of its own!), but a brief look at grammar is useful to understand the different syntax of each templating framework.

A grammar is a logical structure that defines what is acceptable in a language. Although templating frameworks can have a grammar, they aren’t necessarily languages on their own.

Lets look at the handlebars templating framework:

A handlebars expression starts with the tokens  {{ , and contains three sections:

  • An optional additional  { token
  • An optional logic expression :  #with , #using , #if , #else , #unless
  • A variable or object

Once defined, a basic grammar can be represented as a regular expression. Regular expressions can be represented differently in different languages, but this one should be generic enough:

{{{?(#[a-z]+ )?[a-z]+.[a-z]*}?}}

Meaning:

  • Match the string  {{ (opening token)
  • followed by zero or one  { (unescape token)
  • followed by zero or one  #[a-z]  strings (logic directives)
  • followed by an  [a-z]  string (variable or expression)
  • Followed by zero or more  .[a-z] strings (dot-operator variables)
  • followed by zero or one  } (closing unescape token)
  • followed by the string  }} (closing token)

Grammars can be wildly complex, but these simple principles can be applied to any of the templating frameworks to get a better understanding of how they work.

Parsing

Regular expressions are not only useful for understanding how a templates syntax is structured, but are also used in parsing inline-token syntax templates.

Handlebars’ parser uses a technique which involves searching a template for the  {{ token, then “looking ahead” for the closing  }}, and saving everything between the two in a buffer. When the end token is found, the buffer contents are then parsed and types are returned based on their content.

The contents of those blocks are then passed again into the same parser, to look for further operators:

After the parser has finished iterating on the template string, it is left with a stack of logical operations and functions which are then supplied the data for rendering.

Consistency leads to Predictability

One of the keys to a language’s (and templating engine’s) success and adoption is consistency in syntax. Based on previous experience with a given syntax, a programmer should be able to successfully create new code without diving into the documentation. “If that similar structure took a key-value-pair before, I bet this one here does too.”

Inline-token syntax parsers self-enforce consistency of the language, due to the nature of the parser. It must find a specific token, followed by a set of allowable expressions, which themselves might contain expressions. It’s easy to remember that an underscore block always looks like this  <@= ... @>, because it must per the parser.

Element-attribute syntaxes have a harder time enforcing consistency, and it must be created through the framework creators insistence on following a pattern for their “language.”

A generic element-attribute syntax could consist of

Framework creators must choose a pattern for their element-attributes and insist that the pattern is followed for new directives that are added to the language.

Let’s create a pretend framework, called Bob. Bob’s starts simply, and only binds strings:

We continue to use Bob, and need to add some logic:

And later, repeating sections. Since repeat doesn’t really need a value, let’s write it like so:

Now we need to replace multiple attributes:

And finally, replace specific strings within attributes:

The moment a second programmer tries to implement Bob, it becomes clear that we’ve implemented a totally unpredictable syntax! Is a directive part of the attribute name ( bob-string="name"), or in the value ( bob="repeat")? What is the valid syntax for a  bob-bind attribute? A single value or a key-value pair? The  bob-replace value is JSON apparently?

Regardless of the frameworks speed or other technical features, a syntax implemented in this way will kill adoption.

Comparison of popular framework syntaxes

String insertion

angular
closure
handlebars
knockout
pure
underscore

Iteration

angular
closure
handlebars
knockout
pure
underscore

If

angular
closure
handlebars
knockout
pure
underscore

That’s all folks!

Templating frameworks are very useful, and their syntax is one of the main way which a programmer interacts with them. Understanding the differences that syntaxes and template philosophies can help you choose the right one for your use-case!

Arabic web design and web fonts

Going a little way towards displaying Arabic is a native way creates a delightful user experience. Arabic Web-fonts, layout, and language CSS help create that experience.

header

An Arabic speaking translator and web content-producer recently told me

The state of web support for Arabic and other right-to-left language speakers has historically been so poor, that making efforts to properly display their language can create an exceptionally delightful experience for the users.

In the course of development for a multi-language website, I’ve had the wonderful opportunity to explore some of the ways to create “delightful experiences” for these users, mostly focusing on font-selection and typography, and page layout.

Font choice and Typography

System Fonts

The fonts used on the web for Arabic are unfortunately still limited to the default Ariel, Verdana, Tahoma and most of the time the font used is Tahoma because it is the most legible on the web. – http://www.smashingmagazine.com/2010/09/19/showcase-of-web-design-in-the-arab-world/

Web Fonts

Although there are many beautiful Arabic fonts (from calligraphic to modern), the selection of web-font choice is limited. While latin web-fonts are widely available from Google Fonts, Typekit, and other similar services — Arabic fonts are only currently (April 2014) available in Google’s “Early Access” program. This program  showcases fonts that Google will consider mainstreaming with their other Web Fonts, if they are popular and get enough usage. Therefore, fonts in this program have no guarantee of long-term availability.

Many fonts are available from the Early Access program, the following is a curated list with previews of Arabic Fonts. Because of possible limited availability, I’ve provided the previews in image format. Visit my CodePen for full code previews.

Amiri

amiri

Droid Arabic Kufi

droid-kufi

Droid Arabic Naskh

droid-naskh

Lateef

lateef

Scheherazade

shaherazad

Thabit

thabit

Layout

Arabic is a RTL (right-to-left) language. Not only is the text read and displayed from right-to-left, but pages are layed-out right-to-left as well. Ideally, an Arabic translation of an English page would not only flip the text, but “mirror” as much of the page as possible.

mirror-site

CSS

There are a few CSS rules to keep in-mind when developing Arabic (and other RTL) language web-pages.

direction:ltr|rtl (docs) changes the text flow of block level elements and text. It will not, however affect the layout of the page.

float:right|left Remember to float left things right, and right things left

:before :after Some things (like icons) in pseudo-elements can be repositioned by changing :before’s to :afters. These will often require custom CSS as many pseudo-elements are positioned relatively to their parent.

Faded gradient separator bars

Here is a technique for creating both horizontal and vertical separator bars with pure css.

See the Pen Sexyline 2 – verticlal by Michael Jasper (@mdjasper) on CodePen

Using CSS3 radial gradients positioned off element, just the tip of the gradient is show, giving the line a nice shadowed/faded look:

This technique can be applied to <hr>  tags for semantic breaks in content, or they can be applied to any element or class as an effect.

See the Pen Sexyline 2 by Michael Jasper (@mdjasper) on CodePen

Properly aligning and wrapping image captions

Easily align and wrap captions to images of unknown size with two relatively unknown CSS properties.

I recently learned a new css trick to align and wrap captions properly to images of unknown size.  This is a common problem when dealing with any content management system that allows users to upload images to pages or articles.

The problem:

This is a caption of slightly longer length. It should wrap, regardless of the size of the image.

The css solution:

This is a caption of slightly longer length. It should wrap, regardless of the size of the image.

Voilà!

Front-end Series: JavaScript debugging tips and tricks

Note: many of these tips are written with Chrome in mind, but are applicable to any modern browser with developer tools.

  1. Understand what is happening in your code
  2. Set and use Breakpoints
  3. Use the Console api
  4. De-minify
  5. Modify scripts locally
  6. Use a Unit-Testing framework

1. Understand what is happening in your code

A prerequisite to debugging is understanding the code in question. Before debugging, you should be able to answer: what is the purpose of this function? What should the parameters be? How will this line affect local and global variables?

Basically, run the code mentally before trying to debug.

2. Set and use Breakpoints

Once you understand how the code should function, set execution breakpoints at key places. When reached, a breakpoint will pause the execution of script on that line. You can then “step-through” the code one line at a time. This view also allows you to inspect any global or local values to ensure they are what you expect them to be. Often times, you can observe a variable which should contain a value, but is undefined. From there it is easy to trace your way back up and see where the error is occurring.

Breakpoints can be set by clicking on the line-number in the script tab of chrome developer tools, or programmatically using the  debugger; directive.

debug-breakpoints

Use the console api

While sprinkling a few  console.log ‘s sparingly throughout your code can be useful, the console api has many useful functions that might serve the purpose better. Here are a few console api methods I have found useful:

console.dir

Displays all the properties of an object.

console.dir

 console.table

Formats arrays and objects as tables, and allows sorting on columns.
console.table

console.time

Starts and stops a timer (string tag based), logs time (in ms) of intermediate code.
console.time

console.memory

Returns heap information for this process.
console.memory

console.trace

Returns a stack trace for the function where it is called.

console.trace

4. De-minify

When debugging, it can be very frustrating to see an error like:

When at all possible, swap out the minified version for a full expanded and commented version of the script.

When a full version is not available, Chrome’s developer tools come to the rescue. The curly brace button below the script will automatically expand lines for better breakpointing and debugging. It does not however rename obfuscated variable names.
de-minify

Minification bugs

Every so often, you can run into the maddening bug of a full script working, and the same minified script breaking. Luckily, these bugs often attributable to one of a few small problems (mostly having to do with missing semicolons).

For example:

These bugs can also creep in from preceding scripts, or when multiple scripts are concatenated together. This is the reason that jQuery plugins typically start with a  ; . It is a preventative measure against misbehaving code above it.

5. Modify scripts locally

Chrome allows you to modify script files and run them locally. Simply double click into source file, type, and CTRL-S to save. Not much more to explain, but very useful trick!

6. Use a Unit Testing framework

There are a handful of very good third-party unit-testing frameworks for JavaScript, each with their own philosophy and syntax.

See this great Stack Overflow post for many more.

Front-end Series: Part 1 – Architecture

This is part 1 in the Front-end Series. As a front-end developer at a large organization, I work daily on architecture, performance, automation, localization, and compatibility, and other topics which I will share during this series. Feel free to post topic ideas in the comment section!

Large scale web application architecture is much more than a server and a /www folder. The build process can scale with need, but the basic setup contains building assets to a development area, then production environment, caching, and delivery via cdn.

This is example architecture diagram — showing building to different environments, pushing to cdn boxes, and caching.

Front-end-archetecture

Building static assets via source control

Working with other developers at any scale necessitates use of a version control system. Whether Git, Subversion, Mercurial, or the next new hotness, a DVCS is an absolute must. After developing in a local environment, assets are pushed to a development version-controlled server.

The assets here are never directly used by the application, but are pushed to a CDN server (or a mock-cdn for development).  The source control and CDN can be can be synchronized by a few different methods:

  • CRON task that rebuilds one folder from the other
  • Post-commit hook that runs similar script
  • 3rd party build software, like Anthill

Server environments, or “lanes”

It’s necessary to duplicate asset servers for different audiences. The most basic are:

  • Development
  • Testing
  • Staging
  • Production

A typical pipeline is:

  • Assets are developed locally
  • Files are moved into the Development environment to be integrated with other developers work and preliminary tested
  • Quality Assurance tests the application.  Feedback provided to developers (loop back)
  • Once testing is successful,  the assets are moved to the staging server, which serves as a place for stakeholders to preview the application, and approve it for production
  • When okay-ed, the files are moved to production where they are publicly accessible. They are now “live”

Caching and Content Delivery

Linking directly to assets on a server is an excellent way to kill your site, when it goes viral (the Reddit hug of death, or the slashdot effect). The most basic level of defense is on server caching. On smaller sites, this can be an effective protection. Many CMS’s (like WordPress) have plugins that can caching dynamic content (php generated files saved as static html). WP-SuperCache is an excellent example of this layer of defense.

The second layer of defense is a Caching Appliance. This is a server (or cluster of servers) that specializes in serving static files with extreme speed. This appliance has only one function, which allows it to maximize its resources for the one purpose of serving content.

The top layer for serving files is utilizing a Content Delivery Network to distribute and cache assets globally.  At it’s core, a CDN is a network of servers placed in strategic locations around the world, each containing duplicate and synchronized files. These servers, ideally located on backbone connections, serve files to customers quickly in different areas of the globe. For example, a user in France is served assets from a UK server, rather then making the transatlantic trip to Virginia.

For smaller sites (such as this one) there are free or inexpensive CDN options. This website uses CloudFlare to serve static assets to viewers (your CSS file was probably served from this CDN, reducing my server load. Yay!) An excellent CDN for large-scale websites is Akamai. You’ve almost certainly been served assets from Akamai (Facebook, Adobe, Microsoft, and many more use it).  If you’re in the market, take a look at CloudFront as well.

So there you have it: The front-end build and architecture for one of the largest publishing organizations in the world!

Big Picture

What I’ve described is the front-end server and building process for a large scale web application. This setup will typically be mirrored by the application codebase (back-end).

back-end-architecture

Comments, feedback or criticism? Let me know in the comments:

Software Engineering principles applied to CSS

Some of my thoughts about CSS developent. Think of more? Share in the comments and I’ll add them to this page!

Low Coupling

The principle of low coupling suggests that distinct parts of an application be as “stand-alone” as possible.

To illustrate: A very decoupled program could be available from the command-line first, then a GUI is built using that programs API’s. This ensures that the logic of the program is decoupled from the presentation. A developer can change the internal workings of the program without affecting the other aspects of the architecture.

Targeting elements based on their DOM order tangles up the visual presentation (CSS) with the structured content (HTML) – Highly coupling the presentation with the content.

Changing the name of your parent container shouldn’t detach your horizontal menu from its style.

Separate the presentation from the structure with the use of classes:

High Cohesion

Separating the concerns of CSS into different files allows you to create highly cohesive classes that, once in place, allow a great deal of flexibility in development. Areas of concern are:

  • Layout: positioning of elements, geometric dimensions
  • Style: colors, borders, backgrounds
  • Normalization: typography, element defaults

Separating the CSS into separate areas allows you to create highly cohesive “modularized” rules that have the bonus of being easily swappable:

  • Layout-full.css, layout-compact.css
  • Blue.css, green.css, red.css
  • Normalize.css

Any combination of the above files could be used to alter the presentation of the application without changing the content architecture.

Inheritance

If elements are targeted by semantic classes, instead of their order in the DOM, it is easy to modularize classes using the principle of inheritance:

This is a popular technique in many rapid development frameworks, such as Bootstrap, Zurb, and others.

Additionally, CSS may use the principle of multiple inheritance by using styles from multiple sources – such as a horizontal navigation getting its form and function from layout.css, and its color and branding from color.css files.

Generalization

In software engineering, the most general use-case is often sought, as it will eliminate redundant future work. Nathanial Borenstien, inventor of the MIME type once said,

“It should be noted that no ethically-trained software engineer would ever consent to write a DestroyBaghdad procedure. Basic professional ethics would instead require him to write a DestroyCity procedure, to which Baghdad could be given as a parameter.”

Name classes based on their general use-case, rather than on their appearance, position, or other attribute.

If not, ‘The boss’ might ask you to change the submit button to green, but the in-code class will stay .button-blue  forever, because it is already in hundreds of places.

Naming classes on their general case avoids this problem, and also makes for easy discovery and maintenance by future programmers, or your future self.

Additionally, duplication of elements becomes easier. If not, you might need to duplicate the element somewhere other than the original place, and you end up with navigation in the footer called  .sidebar-nav

Abstraction

If using the principle of generalization, there may be some base class that is never intended to be used on an element on its own. To provide some level of abstraction, only declare universal attributes on parent classes.

Encapsulation (private styles)

By using the principle of inheritance, we can make some classes essentially private by namespacing their selector rules:

This ensures our style definitions don’t ‘leak’ into other elements, and can only be used within a specified parent element.

Custom events system in JavaScript – LightEvents.js

Needing an event subscription and publishing system for a HTML5/canvas game I’m creating, I wrote a very light event system.

Anything than can call JavaScript (link, button, etc) can raise an event:

LightEvents.publishEvent('event name', data);

Subscribing to events is equally easy:

Here is the LightEvents object, demo is embedded below

JS Bin

Quick and reliable ad-rotator

In the course of my work, I’ve created and refined a simple ad rotator. It is built in JavaScript, and does not rely on any library, like jQuery, to function.  In my experience, it defeats ad-block, and loads easily on all mobile, tablet, and desktop browsers.

The rotator can be included multiple places on one page without any conflicts or collisions, so just drop-in where needed. Some coding is required to customize — basically copying and pasting your links and image urls, but nothing too heavy.

 

Creating a microformat / richsnippits resume

What are microformats?

Microformats are small patterns of HTML to represent commonly published things like peopleeventsblog postsreviewsand tags in web pages.

Microformats are the quickest & simplest way to provide an API to the information on your website. See what else you can do with microformats.

Have you ever searched for a recipe on Google, and wondered how the highlight data like ingredients or cook time on the search results? Microformats. Or, wondered how they can aggregate reviews, locations, and prices for a restaurant search? Microformats.

Make your resume semantically searchable and available by implementing microformats.

There are several types we will implement from the microformat standard, schema.org, for fields on our resume:

  • http://schema.org/Person
  • http://schema.org/PostalAddress
  • http://schema.org/CollegeOrUniversity
  • http://schema.org/Organization

Resume Sample

View the resume here, and a Google’s report on extracted data here.