Archive for October, 2011

Organizing Mobile

When organizing content and actions on mobile, solid information architecture principles like clear labeling, balanced breadth and depth, and appropriate mental models remain important. But the organization of mobile web experiences must also align with how people use their mobile devices and why; emphasize content over navigation; provide relevant options for exploration and pivoting; maintain clarity and focus; and align with mobile behaviors. In this exclusive excerpt from his new book, Mobile First!, Luke Wroblewski explains how to do all that.

Personality in Design

Personality is the mysterious force that attracts us to certain people and repels us from others. Because personality greatly influences our decision-making process, it can be a powerful tool in design. In an exclusive excerpt from his spanking new book Designing For Emotion, Aarron Walter shows us how to create a strong human connection in human-computer interaction by turning our design interactions into conversations, imbuing mechanical "interactions" with distinctively human elements, and using design and language techniques to craft a living personality for your website.

How Disregarding Design Limits The Power Of Content





 



 


It appears to be a reader’s market. More written content is freely available than ever before, accessible in just about every format you could imagine. If you want it on paper, you’ve got it. On screen? What size, friend? We can shrink, stretch and stitch it all together every which way because, really, we’re just talking about words here… Or are we?

As soon as I ask that question, several others quickly follow:

  • Is content so flexible?
  • Is content’s most basic unit the word? Or is it, perhaps, the message?
  • In today’s reader’s market, what of the writers and the designers who make reading possible?
  • And are we building tools that honor their work, too?

These questions didn’t randomly pop into my head one day. Nor did a design problem get me thinking along these lines. It was while reading — for pleasure — that I noticed something was wrong. After experimenting with a few different services that let me save articles to read later in a much more reader-friendly format (what I’ve come to call “reading advocacyâ€� tools) it occurred to me that in the process of extracting content from its original context and accessing it elsewhere, I might be losing some information along the way.

I decided to see for myself by examining several pieces of content and comparing how they look and function in a variety of incarnations: the printed page, the Web and eReaders. What I found was both encouraging and, for a designer who loves to read and write, slightly troubling. I’ll warn you in advance: there are many examples below, but I think they’re all necessary in order to convey an accurate picture of just what happens to content when we start moving it around. To properly set it up, let’s first briefly look back in history.

A Very Brief History of Content and Design

Long ago, when we humans first began writing things down, there wasn’t a clear difference between pictures and words. In the earliest examples of writing, symbols depicted nameable things — a bird, a mountain, fire, rain. You could combine a few pictograms to communicate something more sophisticated, but that got writers only so far. Some concepts are difficult to describe with images alone. The development of primitive accounting records, though, further abstracted writing.

In order to properly document the wealth and splendor of their kings, Sumerian scribes had to repeatedly etch up to hundreds of animal pictograms onto clay tablets. Cow after cow after cow. Sheep after sheep after sheep. You can imagine how extreme repetition would abstract the symbols they used: the simpler the character, the faster the etching.

writingexamples
On the left, an example of logographic writing. On the right, an example of syllabic writing. (Source: Wikipedia)

Even though the leap from logographic (i.e. symbols that represent words) and syllabic (i.e. symbols that represent sounds) writing to alphabetic systems that approximate what we would recognize today was a profound one — believe me, I just simplified around 2,500 years of the history of writing right there — we still had quite a way to go. After all, the earliest example of punctuation didn’t come until about 840 BCE, when the battle victories of a Jordanian ruler named Mesha were carved in stone for posterity.

Distinguishing between upper and lowercase letters didn’t happen until much, much later, and it didn’t really take off until literacy expanded greatly — say, after the printing press. Imagine reading anything today without capitalization or punctuation. But you’re not reading this for a history lesson. The story of writing is far too big to be told here. And really, I have no business telling it. Yet skimming the surface of history reveals a deeper relationship between images and words than we often realize.

Sometimes words are enough. Other times, they need accompaniment. Even the arrangement of words can carry meaning. Let’s look at a practical example.

Even Basic Formatting Carries Meaning

recipe

What you’re looking at above is a recipe for cookies. (Very delicious cookies, I might add.) I realize it’s difficult to read, but the fact that these three images are small enough to fit nicely on this page actually serves an important point.

Look at the image on the left. Can you make out what kind of information the text is conveying? It’s not impossible, but it will take you a bit of time and squinting at the words to figure out what they are about in general. But as you make your way to the right, the job gets progressively easier. The words haven’t changed, but the way they are formatted has. Formatting, which is really just the way information is organized and arranged on the page, is design in its most basic sense. So, you might also say that as the attention paid to the design of this recipe increases, the more immediately recognizable its content becomes — and the more useful it becomes to an aspiring baker.

The simple lesson of this recipe is that formatting is more than just an aesthetic, secondary treatment of information. Formatting in and of itself contains information that enables the reader to better perceive the nature of the text or, in other words, the kind of message it contains. In the case of this recipe, the cookies produced by any of the three versions would be equally good, but the likelihood that the cookies would be made at all depends directly on the recipe’s formatting. Most would not quickly recognize that the version on the left is a recipe at all; you’d probably recognize the one on the right immediately.

Anyone interested in communicating more effectively should reflect on the degree to which the format — or lack thereof — of their content supports or undermines the content’s message.

Fortunately, we’re pretty good at preserving formatting that is critical to the meaning of written content. If I put the best-formatted version of my recipe on the Web, I’d be confident that readers would see it that way whether they printed it out or read it off the screen. The basics of formatting — fonts, line breaks, numbered and bulleted lists, etc. — are easily implemented and transferred, regardless of the context.

But sometimes the design of a page carries meaning that is substantially visual and that is not so easily preserved because it’s not a matter of simple formatting. History again provides a helpful example.

One More Brief Trip Back in Time

The image below comes from one of the most well-known illuminated manuscripts, The Book of Kells, famous for an extravagance in visual detail found in very few manuscripts like it. Written in Latin, this Gospel book is believed to have been created sometime around the year 800 by Celtic monks living in the Abbey of Kells in Ireland.

bookofkells

What is immediately obvious is that this manuscript was not created merely to transmit the text contained therein. While the message of the text was central to the lives of the monks — religiously, culturally, even practically — the creation of the manuscript was an art that brought life to the book’s deeper meaning and its role in the tradition that coalesced around it. In other words, the role of design and imagery in the illuminated manuscripts was not one of formatting. It had less to do with utility — making reading easier — than with meaningful expression. Its entire purpose would be lost if the text and imagery were separated.

What the earliest writing, my cookie recipe and the illuminated manuscripts all have to teach us is that design — whether in the most basic features of a line of text or in the subtle juxtaposition of words and imagery — is integral to the transmission of meaning and cannot be isolated from the content.

Content And Design On The Web

So far, this all makes sense from the perspective of design philosophy. But how does the relationship between design and content play out in practice? To investigate this, I’d like to share several real-world examples of how context affects content — the examples I promised at the beginning of this article.

1. Interconnected

mattwebb1

Interconnected is the personal website of Matt Webb, the CEO of Berg, a wonderful design studio in London. As you can see, Matt has kept his website’s design very minimal. In fact, besides the fact that Matt is a very interesting person and I’ve been cyberstalking him for years, I chose his website as my first example precisely because it’s so minimal. But let’s see what this same blog post looks like when I save it to read later in my Readability account.

mattwebb2

As you can see, reading Matt’s blog in Readability, instead of on his website, is not a substantially different experience. The colors and typography are different, and Readability includes its own toolbar on the left; but really, nothing here has changed enough to alter Matt’s message.

Let’s compare one more tool: Safari’s Reader, which detects articles and enables visitors to read them in an isolated, attention-friendly overlay.

mattwebb3

Again, no major differences here. Just as with Readability, Safari has altered the colors and typography. But because Matt’s website is so stark to begin with, the experience is remarkably stable across these different contexts.

But what about an article from a website with a much more developed design? How might my experience of the content change from the original context to Readability and Safari Reader?

2. Smashing Magazine

smashingmagazine1

For my second example, I took a screenshot of an article I wrote for this website back in May 2010, “Holistic Web Browsing: Trends of the Future.� As you can see, Smashing Magazine’s design is relatively simple; but, unlike Matt Webb’s design, it includes many more images: a graphic menu at the top, a logo and, as is common in big publications, advertisements.

Let’s see how this article looks in Readability:

smashingmagazine2

What’s immediately obvious is that Readability isolates the content in the main column and, in doing so, strips out just about everything else: the header, logo, navigation and sidebar content. It also removes the ads that Smashing Magazine runs in the content column at the top of articles, but leaves the “Advertisement� tag.

smashingmagazine3

Safari Reader includes the ad in the content column. Other than that, the experience is very similar.

Other than the fact that both tools effectively un-brand Smashing Magazine’s content, there’s not a whole lot to complain about here. No essential elements are missing, and because Smashing Magazine’s authors know to keep the images in their articles very basic (i.e. image references only), there’s little need to worry about losing those aspects of the message that appear in image form.

3. Craig Mod

Craig Mod is another interesting person who has been doing a lot of thinking, writing, speaking and designing related to the content experience for some time now. I’ve chosen his website partly because an article of his is relevant to the discussion, but also because I was curious how his beautiful design would translate to a tool like Readability.

craigmod1

Before I show you this particular article, “Books in the Age of the iPad,� in Readability, I want to quickly share a couple of reasons why Craig’s design makes for a great reading experience. First, it has white space. A lot of it. The screenshot above shows only a small portion of the page. Follow the link above to see for yourself; the article has a single column of text and many high-quality images that Craig has arranged to fit seamlessly into both the article and the website. Nothing feels as if it doesn’t belong.

Secondly, the typography — from the large illustrated title at the top to the headings and two-column preamble — contributes to a mood of calm yet earnest thoughtfulness, which I really appreciate as I slowly make my way through Craig’s argument. He uses design to guide me at a very deliberate pace.

I could go on and on. Suffice it to say that Craig knows what he’s doing with his design. And while the website might appear similarly minimal to Matt Webb’s, the language of design is used very differently here. I’m a fan.

craigmod2

Above is the same article in Readability. At first glance, it doesn’t look too bad. As in the other examples, the typography has changed, as have some of the subtleties of Craig’s layout. But then I realized something: Readability excludes the entire preamble! Everything from “Print is dying…� to “This is a conversation…� is completely gone. I went back to the original page and saved it again in Readability just to double-check. Same thing. I triple-checked. Same thing. Also, look closely at the last paragraph in the screenshot above. For some reason, Readability doesn’t like Craig’s em dashes.

OK, I’ll save you the repetition and skip Safari Reader for this example. (It looks very much like the other two examples.)

Seeing Craig’s website in Readability was a disappointment. After seeing the other examples, I was prepared to lose his design sensibilities, but I wasn’t prepared to lose such a sizeable chunk of content. Clearly, the way Craig has laid out his page’s template doesn’t jibe with the code that Readability looks for to identify where a page’s main content begins and ends, and that’s not really anyone’s fault.

Readability should not — and could not, really — be expected to adapt to and interpret every conceivable way that a Web page can display content, nor should Craig have anticipated how Readability works when designing his website. It’s not about failure so much as about understanding that communication on the Web is done in a variety of ways.

But Wait! It’s Not Just About Pickiness…

Dwelling on the mostly minor differences between how these articles appear may seem overly picky. After all, it’s not like you can’t read them. But even the minor differences — whether a substitution of typography, a change in color or an omission of imagery — are meaningful to the designers who created the original environments in which these articles exist. In my experience, I’ve known plenty of developers who take a casual attitude to implementing designs, but I’ve never met a single designer who doesn’t consider even the smallest detail sacrosanct.

There is also an irony here worth noting. Tools like Readability — and I’m focusing on it mainly because it does reading advocacy the best — are very well designed. They speak the designer’s language by paying attention to details that usually only those who have worked with typography would consciously recognize. The rest of us just see the page and know that it looks beautiful and feels good to read. Designers recognize in Readability an appreciation of white space, proportion, typography and other essentials that are typically considered luxuries on the Web.

That’s why they are so excited about it. Nevertheless, elegant as it may be, Readability substitutes the deliberately unique design of an article with a one-size-fits-all boilerplate aesthetic. While I’m confident in the integrity and best intentions of Readability, I also question the dynamic that it potentially establishes: by adeptly harnessing the seductive power of good design, it attracts the very people who its functionality ultimately undermines.

What to do?

Content And Design In eBooks

Because being able to focus more precisely is the main reason to use reading-advocacy tools, it occurred to me that other content — besides articles written for regular print and Web publications — might present similar difficulties to this system we’re building around content portability. I can think of one huge category in particular that is experiencing the growing pains of the analog-to-digital transition: books.

I chose several books to test what I did with the Web pages: view them first in their “native� format (as printed volumes) and then in their “portable� format (as eBooks).

1. Extremely Loud and Incredibly Close, by Jonathan Safran Foer

In Extremely Loud and Incredibly Close, Jonathan Safran Foer tells the story of a 9-year-old boy who embarks on a quest to learn more about a mysterious key left behind by his father, a victim of the 9/11 attacks. Foer experiments with image and text a great deal in this book, making for a perfect opportunity to see how the printed page translates to eBook format.

extremelyloudandincrediblyclose1

The scan above shows the first two pages of a chapter that “appears� to still be in draft form. I was immediately curious how the eBook would represent the red editorial marks in the text.

extremelyloudandincrediblyclose2

As you can see, the eBook doesn’t handle them very well. There doesn’t seem to be much rhyme or reason to the characters that the eBook inserts to represent the edges of the red circles. Sometimes they’re parentheses, other times uppercase letter. Either way, the text is pretty difficult to read.

extremelyloudandincrediblyclose3

In case you were thinking, “Hey, that’s not so bad!�, above is a screenshot of the next page in the eBook, where things get considerably worse. Adding in slices of images of the original printed page doesn’t help.

2. The Raw Shark Texts, by Steven Hall

The next example is The Raw Shark Texts, a strange mystery novel about memory and reality (among other things) by Steven Hall. The story takes place in a world much like our own, except that it is also home to “conceptual creaturesâ€� that feed on ideas. As I said, it’s a strange book — so strange that the text itself veers off into experimental visual oddities, too.

rawsharktexts1

In the scan of the printed book above, I’ve isolated a calligram of a fish made of text (which makes sense — sort of — in the story). Let’s see how the eBook handles this.

rawsharktexts2

In some ways, the eBook format handles Hall’s fish images better than Foer’s editorial markings. In particular, no junk characters are inserted in the text. But it’s not the greatest representation of what Hall had in mind. In the printed book, the “fossil fish reconstruction� occupies the entire page, with its description underneath. In the eBook version, the image is reduced in size and put on the same page as text that refers to an image not shown, while the “fossil fish reconstruction� footnote is bumped to the next screen.

Obviously, the eBook doesn’t stick with the printed version’s design — nor does it really try to. This makes for a more confusing reading experience.

3–4. The Stars My Destination, by Alfred Bester, and The Medium Is the Message by Marshall McLuhan and Quentin Fiore

Neither of these books is available as an eBook in the Kindle, iBooks, or Google Books marketplaces. An EPUB version of The Stars My Destination is floating around on the Web, but it is not an authorized version, so I don’t expect that it handles the original design with any reverence.

But both of these books serve as great examples of how the message can depend on more than just traditional text.

starsmydestination1

In one of the later chapters of The Stars My Destination (shown above), Bester’s protagonist experiences an almost psychedelic trip through time and space, which the book captures with an illustration of the words that adds a visual layer to the description, similar to concrete poetry.

Something like this could be easily preserved in an eBook by inserting images in the flow of text. But the particular words that Bester illustrates would have to be added as some kind of meta data in order for the text to be fully indexed and searchable.

mediumisthemassage

Finally, what fusion of image and text is more relevant than The Medium Is the Message, by Marshall McLuhan and Quentin Fiore? You’ve probably already guessed that the title of this article is an homage to this book. The scan above (no, I didn’t accidentally reverse it — that’s actually how it is printed) is just one example of how the pages of the book are all uniquely designed to illustrate McLuhan’s text in a striking visual and typographic style. Fiore, by the way, is a graphic designer, not a writer, who reached out to McLuhan to collaborate on the book, specifically to explore how text and image can be combined to affect the consciousness of the reader.

If you’re looking for one book that in its very existence emphatically represents the diverse nature of content and pushes its boundaries far beyond text alone, this is it.

Am I Just Being Picky Again?

Maybe so. Like the Web pages that I looked at earlier, none of these eBooks have been adapted poorly enough from print to be impossible to read. After all, Google Books gives you the option to read both the scanned pages and the “flowing textâ€� version. So, in any of these situations, you do have alternatives. Of course, depending on your screen’s size, the scanned version might be less than optimal — you might have to scroll up and down so much that you’d be too annoyed to bother with it.

Not every book will suffer the analog-to-digital transition. Only those that subtly interweave text and image (and some even that embed illustrations in the text the traditional way) will slip through the cracks of what is, currently, a fairly simple system.

But what these eBooks continue to make clear — reinforcing our argument that emerged from tracing written language from its roots to today’s awkward technological transition — is that written communication is complex. More complex than just lines of text. Just because an author uses a variety of means of communication — including text, images, and images created from text — their book should not be disqualified from being made available in digital form, nor be handicapped when it is made available. After all, it’s not the book’s fault that our current approach to digitization favors works that adhere to a rigid distinction between text and image.

Content And Design In The Future

What these reading-advocacy systems need now is design advocacy — an expansion of the templates and tools that, on the one hand, honor the intended substance and meaning of the author’s text and that, on the other, don’t reduce the reader’s experience of content to one of merely processing text.

Coincidentally, GOOD Magazine just recently issued a challenge to its readers: redesign a news website using only images — no text allowed. The magazine doesn’t explain where this idea came from, but would it be a stretch to imagine that it signifies a boredom with text and a desire to return to our roots and explore communication with symbols again? Perhaps. I certainly look forward to seeing what GOOD’s readers come up with.

In the meantime, we all need to give serious thought to how design and content interact. I think portability is a great idea — see Cameron Koczon’s piece on “Orbital Contentâ€� for a focused argument on “content liberationâ€� — but it would be a shame to narrow down the designed content experience to only what can be easily translated to third-party reader tools. Imagery, and especially the subtle interplay of imagery and text, deserve to remain active parts of digital expression. Our goal, whether we’re designers or writers, should be to make this happen. Maybe the Readability team is already thinking through these issues and coming up with new ways to translate content. If so, I’d love to hear about it.

I’ll admit to not having an answer, either. My intent here is to extend the question to you, in the hope that we can figure it out together.

(al) (il)


© Christopher Butler for Smashing Magazine, 2011.


Getting Started With PHP Templating





 



 


In this article, we’ll cover how to separate the view of your PHP application from its other components. We’ll look at why using such an architecture is useful and what tools we can use to accomplish this. Here’s what we’ll cover:

  1. Learn some basic MVC concepts,
  2. Review some popular templating libraries,
  3. Play around with a small custom-made view class.
  4. Explore the basics of using the Twig library.

To fully benefit from this article, you should already know how to write and run your own PHP scripts on a Web server (i.e. using Apache).

A Quick Introduction To The MVC Pattern

In the early days of PHP applications, “spaghetti code� was a familiar sight. Fragments of PHP code were mixed in with HTML mark-up. There were no frameworks, so Web applications were just a bunch of source files. As the PHP language matured, developers started to think about the cleanliness and maintainability of their code. The model-view-controller (MVC) pattern was introduced.

MVC is a software architecture that allows for the separation of business logic from the user interface. In this architecture, the user sees and interacts with the view that, in the case of Web applications, is generated HTML code (along with JavaScript, CSS, images, etc.)

screenshot

User actions are passed (as HTTP requests, GET or POST methods) to the controller. The controller is a piece of code that handles and processes user input and then reads and makes necessary changes to the model, which is responsible for the storage and modification of data. (In simple terms, the model consists of the database structure and contents, and the code used to access it.) Then, the controller generates the proper view that will be sent and displayed to user.

Such separation of layers has many advantages…

Code Is Easier to Maintain

Because the model is separated, changing internal data relations without changing the rest of the application is easier. For example, the model for the user could provide the is_active() method, returning a boolean variable. In the business logic, it would be enough to check what value is returned by this method, without any knowledge of its internals.

You can also check for various conditions (for example, whether the user has confirmed their registration, paid their monthly fee, etc.), and you can change these rules in one place, without having to change anything in the other parts of the code. It also becomes easy to make a platform-independent application that allows for switching between database engines; this is often performed by ORM (object-relational mapper) libraries, which are a sub-layer of the model layer. ORMs add a level of abstraction to the library that accesses the specific database directly.

The Same Content in Multiple Views

Separating the view allows a single result to be presented in different forms. For example, based on some logic, a news page could be displayed in normal, mobile and RSS versions, all using the same content returned from the controller.

More Secure

Variables are escaped by default before being sent to the view, which is useful in applications that display user-generated content. Consider a variable with some unknown HTML or JavaScript code being passed to the view (which should never happen in your application). Escaping the variables prevents malicious code from being injected in such cases.

Better Code

Separating the layers forces the programmer to design better applications that are easier and cheaper to maintain. Also, designers and front-end developers don’t have to work with the business-logic code, because their task is only to display the contents of the variables that are provided to the view. This reduces the risk of the breaking some PHP code.

Today, every modern framework implements the MVC architecture. There are also some libraries that enable you to use selected features of the architecture. In this article, we’ll go over the recipes for the view, and in future articles we’ll cover the model and some ORM libraries.

Overview Of PHP Template Engines

As you might expect, many templating libraries allow you to separate the view layer from the rest of the application. In the most basic scenario, you can implement such a library by yourself (which we’ll do in the next section). You don’t even need a special library; sometimes it is enough just to separate your view (i.e. the template’s HTML files) into a different directory, prepare some variables in the simple controller (usually the main PHP file) and include the templates.

Every modern PHP Web application framework employs some kind of templating engine. Most of them use plain PHP by default (including Symfony 1.x, Zend Framework and CakePHP), but many standalone libraries can be plugged into your favorite framework or custom application.

Smarty

screenshot

Smarty was one of the first and most advanced templating engines. It was developed as a sub-project of the main PHP project, but it has lost its popularity in recent years due to poor performance and forced backward compatibility with PHP 4. It has also lacked many modern features, such as template inheritance. Now, it is rising back to power with version 3. Many other frameworks (such as Twig and Django) have inherited some of the basic concepts laid down by Smarty.

<html>
    <head>
        <title>Info</title>
    </head>
    <body>
        <pre>
            User Information:
            Name: {$name|capitalize}
            Addr: {$address|escape}
            Date: {$smarty.now|date_format:"%b %e, %Y"}
        </pre>
    </body>
</html>

PHPTAL

screenshot

PHPTAL is a template language based on a very different syntax and concept; it implements the Zope Page Templates syntax (Zope is an application server written in Python). It is based on well-formed XML/XHTML, as in this example that comes from the project page:

<div tal:repeat="value values">
    <div>
        <span tal:condition="value/hasDate"
        tal:replace="value/getDate">
            2008-10-06
        </span>
        <a href="sample.html"
        tal:attributes="href value/getUrl"
        tal:content="value/getTitle">
            My item title
        </a>
    </div>
    <div tal:content="value/getContent">
        This is sample content that will be replaced by
        real content when the template is run with real
        data.
    </div>
</div>

If you have prior experience with ZOPE or are a fan of XML, then this template engine is for you.

Twig

screenshot

The last PHP template engine we’ll look at, and the one we’ll focus on in this article, is Twig, from the authors of Symfony, which is the default view library of this framework’s 2.0 version. Its advantages are rich features, extensibility, good documentation, security and speed (it compiles your templates to the native PHP language).

<html>
    <head><title>My first Twig template!</title></head>
    <body>
        My name is {{ name }}.
        My friends are:
        <ul>
        {% for person in friends %}
            <li>{{ person.firstname}} {{ person.lastname }}</li>
        {% endfor %}
        </ul>
    </body>
</html>

The Basic Concept

Knowing how to use a particular library or framework is not enough. A good programmer should also know what is under the hood: how the stuff works, the relationship between the components, and possible caveats. For this reason, we’ll go over the concept with a simple templating library, custom-made for this tutorial. This should give you an idea of how more advanced libraries work. To run this code on your own, you will need to properly configure your HTTP server (with Apache), using PHP 5. No other libraries are needed.

Note: you can download this example code from the Mercurial repository on Bitbucket either by downloading the ZIP file or, if you have a command-line version of Mercurial installed, by entering the following command:
hg clone https://bitbucket.org/krzysztofr/sm-view.

First, let’s look at the code.

MyView.php: Templating Library

<?php
class MyView {
    protected $template_dir = 'templates/';
    protected $vars = array();
    public function __construct($template_dir = null) {
        if ($template_dir !== null) {
            // Check here whether this directory really exists
            $this->template_dir = $template_dir;
        }
    }
    public function render($template_file) {
        if (file_exists($this->template_dir.$template_file)) {
            include $this->template_dir.$template_file;
        } else {
            throw new Exception('no template file ' . $template_file . ' present in directory ' . $this->template_dir);
        }
    }
    public function __set($name, $value) {
        $this->vars[$name] = $value;
    }
    public function __get($name) {
        return $this->vars[$name];
    }
}
?>

The main (and only) class of our templating engine is very simple. We use the “magic methods� (yes, that’s the official name) __set() and __get() to pass variables to the internal repository and then, in the template script, read from it. (A little explanation on magic methods: they are called when you try to read or write to nonexistent properties of the class. You can read more on this topic in the chapter on overloading in the official PHP manual.) As a bonus, I’ve added a configurable template directory.

Invoking our library is straightforward. In this example, I’ve invoked two views, although different templates should be used in the actual application, depending on the application’s logic.

index.php: Controller

<?php
include_once('MyView.php');
$t = new MyView();
$t->friends = array(
    'Rachel', 'Monica', 'Phoebe', 'Chandler', 'Joey', 'Ross'
);
$t->render('index.phtml');
$t->render('index.xml');
?>

The templates look like this…

index.phtml: HTML Template

<html>
    <body>
        Names of my friends:
        <ul>
        <?php foreach ($this->friends as $friend): ?>
            <li><?=$friend?></li>
        <?php endforeach; ?>
        </ul>
    </body>
</html>

index.xml: XML Template

<?='<?xml version="1.0" encoding="utf-8"?>'?>
<myfriends>
    <?php foreach ($this->friends as $friend): ?>
        <friend><?=$friend?></friend>
    <?php endforeach; ?>
</myfriends>

If you have basic knowledge of PHP, you can imagine how this works. Some logic is being used to set the variables, to read them from the database and so on, and then these variables are passed to the object of our view class. Next, we can access these variables in the template file, which is in HTML format, and the second one is XML (but could be in any other: JSON, plain text, CSS, JavaScript, etc.).

That’s the main idea behing the MVC model (without the “M,� in this example): the business logic happens in one place, while the content generation is sent to the user (or view) in another place. From one set of variables, you can generate many different views. In the template, you’re using plain PHP to display the variables.

Twig Library (With Tutorial)

The Twig library basically does the same job as the simple example above, but in a more sophisticated way. It has many useful features that enable you to develop and maintain your projects more easily and quickly.

Installation

Let’s start this short tutorial with the installation. Twig requires PHP 5.2.4 or above, but I assume that a PHP-enabled HTTP server (such as Apache) is already at your disposal. The easiest way to get it is to clone the repository on GitHub:

git clone git://github.com/fabpot/Twig.git

Or you could get it from the SVN repository:

svn co http://svn.twig-project.org/trunk/ twig

Alternatively, you could install it using PEAR:

pear channel-discover pear.twig-project.org
pear install twig/Twig

Lastly, you could get the file from the project’s download page.

Configuring the Environment

Once the library is installed, you can start playing with it. I assume you will prepare your own application logic, which is beyond the scope of this article, so we’ll skip to the part where we already have something to display.

First, we’ll need to include the Twig library and register its autoloader:

require_once './twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

Notice that we have to provide the proper path to the Autoloader.php file, which is in the lib/Twig directory of the downloaded source package. This piece of code enables us to use all of the Twig libraries without having to explicitly include them. You should be familiar with this technique if you use other popular libraries or frameworks (such as Zend Framework and PEAR).

The next essential part of the Twig library is the loader. This is a class that tells the Twig engine how it should load the templates. With the object of this class, we can initialize the main part of the engine, the Twig environment. Here’s an example:

$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
    'cache' => './tmp/cache',
));

In this example, Twig_Loader_Filesystem is initialized with the directory where templates are stored as a parameter. An instance of the loader class is used to initialize the Twig environment as its first parameter. The second parameter is an array of options. The most important of them are these:

  • cacheThe directory where cached templates will be stored (more on the cache later). If you don’t provide a valid path here, the templates will not be cached (which is the default setting). Remember that you have to set the proper permissions for the cache directory so that your script can write there.
  • auto_reloadThis tells Twig to reload the templates every time they change. If it’s set to false, the templates will be reloaded only if you delete the contents of the cache directory. This is useful if you need to improve the performance of your website (and you rarely modify your templates).
  • autoescapeThis determines whether variables are escaped in the view automatically (the default is true).

Twig_Loader_Filesystem is the most common way to load the templates. For a parameter, you can provide a single string variable or (if you have two or more directories with template files) an array of strings. In such situations, Twig looks for the requested template files in the same order as the paths appear in the array.

Another loader that you might want to use in certain situations is Twig_Loader_String, which enables you to provide the template directly in the form of a string. This can be useful if you store your templates in some form other than files in a file system (for example, if you generate them dynamically, store them in the database, store them in some cache, etc.).

Twig is able to speed things up by caching your templates. That is, Twig processes the templates not every time you need them, but only once, when it detects that the template’s contents have changed (if you have enabled the auto_reload option). Pure PHP code is generated and stored in the cache directory. (Look into the cache files to learn about Twig’s internals.)

Templates

So, how do we display our first template? Let’s make it a simple “My name is [your name here]� page, with a list of some other items. First, prepare your template file. It will be very simple, because it contains only the basic output:

<html>
    <head><title>My first Twig template!</title></head>
    <body>
        My name is {{ name }}.
        My friends are:
        <ul>
        {% for person in friends %}
            <li>{{ person.firstname}} {{ person.lastname }}</li>
        {% endfor %}
        </ul>
    </body>
</html>

Save this file in the templates directory. The convention is to save a template with the .phtml extension, so let’s save ours as hello.phtml. Now we’ll prepare the script that will display the template. Its content will be as follows:

<?php
require_once './twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('./templates');
$twig = new Twig_Environment($loader, array(
    'cache' => './tmp/cache',
));
$template = $twig->loadTemplate('hello.phtml');
$params = array(
    'name' => 'Krzysztof',
    'friends' => array(
        array(
            'firstname' => 'John',
            'lastname' => 'Smith'
        ),
        array(
            'firstname' => 'Britney',
            'lastname' => 'Spears'
        ),
        array(
            'firstname' => 'Brad',
            'lastname' => 'Pitt'
        )
    )
);
$template->display($params);
?>

In this code, the Twig autoloader is included and registered. Then, we created the loader from the file system, which looks for the template files in the templates directory in our project’s root. In the next step, the environment is initialized with the previously created loader. We’ve enabled caching as a parameter by providing a path to the cache directory. As a result, the following code is sent to the browser:

<html>
    <head><title>My first Twig template!</title></head>
    <body>
        My name is Krzysztof.
        My friends are:
        <ul>
            <li>John Smith</li>
            <li>Britney Spears</li>
            <li>Brad Pitt</li>
        </ul>
    </body>
</html>

If you look again at the template, you will notice some basic rules:

  • The {{ … }} tag is used to print the variable or expression;
  • The {{% … %}} tag is used for flow-control statements, such as if and foreach;
  • You can access the array elements by using the myarray.item syntax. (It’s actually more sophisticated at the implementation level: it checks for the elements of the array, the object properties and their methods, and it even looks for the methods getItem and isItem — read more about it in the documentation).

But what if you want to send the browser an XML response rather than an HTML file? Nothing could be simpler. Just prepare the XML template, like so:

<?xml version="1.0" encoding="utf-8"?>
    <helloworld myname="{{ name }}">
        <friends>
        {% for person in friends %}
            <friend firstname="{{ person.firstname}}" lastname="{{ person.lastname }}"/>
        {% endfor %}
        </friends>
</helloworld>

Save it as, say, hello.xml in the templates directory. To generate the result, just load this file instead of index.phtml in the PHP script, and you’re done. (Of course, in a real environment you might want to use more sophisticated logic to differentiate between the XML and HTML output).

This example shows how easy it is to use Twig. In the following examples, I will leave out the whole initialization and rendering phase, just to show the relevant pieces of the template’s code.

Filters

Filters are a useful concept and are common to many templating engines. Filters are applied to the variable to change its contents and print it to the template. Take the following code:

{{ myvar|upper }}

This will affect the variable being printed, and all lowercase letters will be switched to uppercase. Filters can be chained, too. So, you could strip out any HTML tags and convert the variable to uppercase with following code:

{{ myvar|striptags|upper }}

Filters can also take parameters. An example is the replace filter, whose purpose is obvious:

{{ "I like Twig."|replace({'like':'love', 'Twig':'you'}) }}

The following filters are built in:

  • date
  • format
  • replace
  • url_encode
  • json_encode
  • title
  • capitalize
  • upper
  • lower
  • striptags
  • join
  • reverse
  • length
  • sort
  • default
  • keys
  • escape
  • e
  • raw
  • merge

Most of these are self-explanatory. You can check the details in the documentation.

Control Structures

In templates, most of the operations you will be doing will be looping over a set of data (listing some items), sometimes accompanied by conditional statements (if … then). This is why Twig has implemented only for and if control structures, but they are quite powerful.

The for loop was presented in its simplest form in the previous section. Below are some more sophisticated examples.

Here is the code to iterate over a sequence of numbers:

{% for i in 0..10 %}
    item number {{ i }}
{% endfor %}

You can do the same with letters:

{% for l in 'a'..'z' %}
    {{ l }}
{% endfor %}

You can use variables and filters on both sides of the .. operator.

To access the keys of an array, you can use the following:

{% for k in myarray|keys %}
    key: {{ k }}
{% endfor %}

To access keys and values at the same time, you can use this:

{% for key, val in myarray %}
    key: {{ key }}, val: {{ val }}
{% else %}
    no items in the array
{% endfor %}

Notice the else block. It is rendered when the array is empty and no iteration takes place.

You may have noticed that the author of Twig was highly inspired by the behavior of the for structure in the Python language.

Important: you cannot use break or continue statements in the Twig version of the for loop. On the other hand, you do have access to a few useful variables inside the loop:

  • loop.index
  • loop.index0The iteration number. It is counted from 1 by default, so use index0 to make the index number start from 0.
  • loop.revindex
  • loop.revindex0This is the same as index0 but counted from the end of the loop.
  • loop.first
  • loop.lastThis is true if it is the first or last iteration in the loop.
  • loop.length

The if statement is almost the same as it is in pure PHP. You can use if, else and elseif tags. For example:

{% if user.role == 'admin' %}
    Hello, administrator!
{% elseif user.role == 'user' %}
    Hello, user!
{% else %}
    You don't have a role defined.
{% endif %}

As with the for loop, the operators in Twig are highly inspired by the ones in Python. For example, here we’ll check whether John is in the list of friends:

{% if 'John' in friends %}

Or you could use a predefined list:

{% if 'John' in ['Bob', 'Dave', 'John', 'Mike'] %}

To negate the value, use the word not, like so:

{% if 'John' not in friends %}

You may want to use tests in conditional statements, in addition to operators. For example:

{% if var is divisibleby(2) %}

Here are the tests that are built in:

  • divisibleby
  • none
  • even
  • odd
  • sameas
  • constant
  • defined
  • empty

This covers most of the basic syntax of Twig. To go deeper, you should read the extensive documentation.

Template Inheritance

As the creator of Twig states, template inheritance is the most powerful and important feature of Twig. It lets you define a main template as the base of other templates depending on the business logic. For example, you could define the base template below and save it to the file layout.phtml, in which you might want to define the basic layout of your website.

<html>
    <head>
        <title>{% block title %}My page{% endblock %}</title>
    </head>
    <body>
        <div id="left-box">{% block leftbox %}This is the left box.{% endblock %}</div>
    <div id="content">{% block content %}{% endblock %}</div>
    </body>
</html>

Then, by calling the template that extends layout.phtml, you will be able to add blocks containing only content in addition to the base template.

{% extends "layout.phtml" %}
{% block title%}{{ parent() }} - About me{% endblock %}
{% block content %}Lorem ipsum dolor sit amet.{% endblock %}

You can call the parent block using the {{ parent() }} function and extend it. If you don’t call a block (leftbox, in this example), its content will be left intact, as is the case with the parent template.

Template inheritance could help you create a flexible template architecture. Read the documentation to learn the details.

Incorporating Twig Into an Existing Project

Because Twig is so flexible an engine, there is no one specific way to incorporate it into your project. You just have to place the Twig library somewhere in your project and create directories for the cache and templates. The locations of all of these are up to you. Furthermore, you can define a PHP script as an entry point to your application, or include and instantiate the Twig object in every script in your project.

Conclusion

I hope you enjoy working with template engines such as Twig and that they increase your productivity and the cleanliness of your code. Good luck!

Further Reading

Here are some websites you might find useful:

(al)


© Krzysztof Rakowski for Smashing Magazine, 2011.


Flash Isn’t Dead Yet!


  

It’s been really popular lately for many professionals to dismiss the use of Flash. Many designers and developers push the idea to discontinue use of the almost 20 year old technology. There are a range of what seems to be problems from the heaviness of Flash projects, the inability to frequently update without tearing everything apart and the difficulty in creating a Flash website with great search engine optimization.

In the meantime, designers and developers are looking towards different technology such as JavaScript, Ajax, Silverlight, HTML5 and CSS3. Many of these technologies are actually wonderful alternatives as they are lighter than Flash and make it a bit easier to work around, as well as many are free and open source technologies. You also have the mobile device argument–where many devices don’t make Flash available on most browsers. However, dismissing the use of Flash is extremely premature.

Flash Site Examples

Flash is still a necessary and great technology to use. Flash can really push the idea of your graphics forward and help come up with a great level of interactivity for audiences. Below is a list of some really great websites to look at, use and understand how useful Flash really is.

Atmozfears

This website exemplifies how you can take a pretty good graphic and make it the centerpiece of an outstanding website. The interaction is much further than that of any other relevant technology without losing an audience.

Being Henry

This is an extremely interesting and progressive concept. It’s a movie, that allows you to choose your story line. This is an amazing idea, because there are books similar to this made popular for children! The use of Flash takes this type of interaction to a new level.

 The Bulitt Agency

Flash is used here to captivate and draw in the audience. It was also used as a great way to showcase some amazing graphics and ideas. The interface is super easy to understand and makes for an overall great website.

Deaf Preachers

Musicians have always got to find a way to stand out from the pack and really make themselves noticeable. This website serves as an interactive music video for the artist. This is a GREAT way to get folks interested in their music as well as their brand.

Eric Stanley Global

Eric Stanley’s website is a typical showcase of his musicianship and artistry, however, it is taken up to that WOW factor with the use of Flash. This site focuses on good design with the special touch used via Flash.

Frontier Room

Another example of how Flash can take a regular idea (like a restaurant website) and turn it into something with a ton of character. From the loading screens to other elements, it definitely stays true to it’s character and adds a bit of humor to their site. (Go to the reservations page to get a laugh out of the moo cow).

GT3 Creative

The great thing about Flash is that there are little to no limits when we are talking about graphics. GT3 Creative did a superb job creating their own little interactive island for potential clients. They claim to be a creative company, why not be as creative as possible?

Nothing Compares to Havana

Aside from that blatant typo, this is another extremely interesting, progressive and interactive website. We had to see it to believe, but basically the site can connect to your microphone, and if you whistle you can navigate throughout the website. Pretty neat for those who can whistle.

Ivan Moreno

It’s getting harder and harder to create a stand out portfolio that gets the attention of potential clients. So, instead of creating a simple website, Ivan decided to make his have a 3D navigational system. This is a simple, yet very effective use of Flash.

Jumpman

There are times when we visit websites just to get a bit of background history on a product and most times when you do that, you get a blurb on how amazing the company is and why the product rocks. Well, in this circumstance, Flash gets us a visually appealing interview on one of the most purchased shoes ever.

Kasulo

This is another great example of taking things to higher levels. The design is very good and the interface let’s you travel throughout the timeline of this portfolio. This is another forward-thinking idea.

La folle journée de Julien

While we aren’t French buffs, we can assume this is another one of those super neat interactive films. However, this site is a bit more graphical and Flash heavy than the former–and simply amazing. Sites like this really draw viewers in.

Lois Jeans

Another great example of crazy good graphics and stellar interactivity. This site is a bit simpler in it’s graphic department, but the Flash is what gives it it’s character. The interaction the mouse has with the entire site also contributes to this design.

I Make My Case

When you decide to purchase or create a cover for your telephone, wouldn’t you like to see what your phone would look like? Have no fear, Flash is here! This website allows you to create a custom cover for your phone and see it in 3D.

Martha Marcy May Marlene

This is the website for a movie that really gets you involved and drawn in to the concept. Many times, folks say you shouldn’t use a Flash type of intro, but it really gets you more and more interested in this film, much like an extended, super awesome trailer. Did we mention that it’s interactive?

Mixr

This is another great portfolio type of site that allows you two different ways to navigate through their featured projects. The use of Flash shines up the presentation a bit and makes this site fairly intuitive.

Music Can Be Fun

One of the most popular and probably most employed uses of Flash is to make games folks can play in their past time. Most games however don’t pay a ton of attention to precise graphics, like this extremely addictive game.

The Neil Young Store

Neil Young is a pretty famous musician who is characterized by his ability to use personal lyrics and make you feel like he’s holding a conversation with you through music. His store and website here almost attempt to do the same by inviting into a place in which he may have really resided or frequented.

The Profiler

This seems to be an application that will convert you and your Facebook friend’s profile pictures into a three-dimensional presentation. It’s a pretty neat app that shows how Flash has the ability to interact with other entities on the web and come up with some pretty neat stuff.

Reusch

There’s something about video that can get people interested in something more so than a bunch of different pictures. This site uses Flash to backdrop a handful of great athletes who use their product.

Sagres – Preta Chocolate

This entire site is composed of pictures taken of the actual chocolate and hand drawn icons and typography. This website is completely thorough and goes to a higher level of branding and being consistent. See how it was made.

Silver Pistol Digital Agency

Graphics can really make or break a site, but  great graphics with great user interface always wins. This website shows off the best of both worlds and uses Flash as a means to spice it up and give a little atmosphere/character with their audio choice.

Tag Galaxy

Much like ‘The Profiler’ site, this one connects to Flickr via tags and brings up whatever pictures you are looking for. This is a very useful site for designers that puts things together in a very visual and understandable way.

Brian Wilson | MLB Always Epic

One word: HILARIOUS. If you don’t know about this guy, he’s an American baseball player with an out of control beard and personality. What better way to make a baseball website than to feature him and an interactive beard?

The Place To Be

Once again, this is an example of using Flash to take what could be a pretty regular site into an amazing web experience. This travel photography type of blog is taken to new heights with it’s graphic design and it’s interactivity.

UCF 116

The UFC put together this site to help promote a past wrestling event, one that claimed to be the largest in their history. Fortunately for us, we can judge accordingly by looking at all the wrestlers and vote on what we feel will happen. This is a very well put together site.

Werkstatt

This example is another great and creative way to showcase a wonderful portfolio website. Instead of creating a nice grid type of view, this site intuitively scrolls side to side to allow you to see this artists work. On this site, Flash adds the extra creativity.

Let Flash Live

People are really interested in killing Flash and being the firsts to really declare that this technology is no more; but as we can see there are many websites that still use it (and it’s still extremely popular overseas). Flash isn’t going anywhere mainly because it’s 20 years worth of technology that we don’t want to flush down the drain. Though there are a ton of alternatives, Flash can do almost anything with it’s ActionScripting and being paired with some good XML.

The second reason Flash isn’t going anywhere is because of the level of interactivity that Flash can bring to the table. Sooner or later social networks won’t be enough; text messaging and watching video’s won’t be enough; everyone will want more interactivity. They will want a better way to look at the people they are connecting with and the companies they are purchasing from. And quite frankly, there aren’t many other relevant technologies that can do it like Adobe Flash, and be so multifaceted.

So, let’s go back to embracing GREAT Flash developments and being awesome innovators. Design can only take you so far, but interactivity and connections can take you so much further.

(rb)


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress