Accueil > Réalisations > Projets Libres > Un framework HTML est-il possible ?

Un framework HTML est-il possible ?

Je suis intervenu lors de la session 2010 de Paris-Web pour présenter une proposition de framework HTML.

Sous un titre un brin intriguant, j’ai présenté quelques propositions autour de l’industrialisation de la production des gabarits HTML sur les projets Web.

Ces propositions prennent la forme d’un Framework, qui s’inspire des travaux réalisés autour du projet Zpip. Il en reprend les solutions aux problèmes génériques indépendants du socle technique.

De ce projet fondateur, il a tiré son nom de "Framework Z", que vous pouvez retrouver sur GitHub

En attendant que je revienne plus en détail sur le sujet ici, la présentation est téléchargeable ci-dessous au format PDF.

J’attends vivement vos retours pour continuer la discussion amorcée par la présentation et faire progresser ce sujet qui me tient à cœur.

Documents joints

Vos commentaires

  • Le 15 octobre 2010 à 23:22, par Jacques Pyrat En réponse à : Un framework HTML est-il possible ?

    Il y a un point qui me manque dans ce qui a été présenté. D’après-moi, une caractéristique que doivent avoir des composants modulaires, c’est de pouvoir « communiquer » entre eux de manière à en modifier le comportement. Autrement dit : se passer des variables.

    Exemple type : j’ai 2 pages : une page d’article, et une page de plan. Pour ces 2 pages, je veux bien sûr un <title>Titre de page</title> différent.
    Le plus simple est depuis le content.php de chacune des page passer dans l’environnement une variable donnant la valeur de ce titre.

    Le fait avec Z de devoir dupliquer des fichiers de template pour reprendre le nom du template principal et mettre la variante spécifique à chaque type de page me semble être à l’opposé de la volonté d’avoir des « blocs » réutilisables.

    Mais peut-être suis-je passé à côté d’un élément qui résout cette question élégamment.

  • Le 16 octobre 2010 à 22:05, par Cedric En réponse à : Un framework HTML est-il possible ?

    Vouloir passer une variable directement d’un bloc à un autre est non pertinent d’un point de vue architectural.

    Comme si, dans un langage, tu voulais directement faire passer une variable d’une fonction A vers une fonction B. C’est une fausse bonne idée qui va exactement au contraire de la modularité et de la réutilisabilité, car cela créé une dépendance entre les deux fonctions.

    A contrario, dans le cas que tu souhaites résoudre, une information peut venir du contexte général et être partagée par A et B (content et meta dans ton cas). Ou le résultat de A peut être fourni à B. Ce sont deux schémas qui fonctionnent sans créer de dépendance.

  • Le 17 octobre 2010 à 13:52, par Loiseau2nuit En réponse à : Un framework HTML est-il possible ?

    Excellent résumé et PDF très concis, bravo !

    Je regrette sincèrement de n’avoir pu voir la prez’ en live mais je ne doute pas une seconde que ça a du très bien se passer :-)

  • Le 18 octobre 2010 à 11:19, par Cedric En réponse à : Un framework HTML est-il possible ?

    Je viens de regarder un peu

    http://jquerymobile.com/

    jQuery Mobile | jQuery Mobile

    Seriously cross-platform with HTML5

    jQuery mobile framework takes the "write less, do more" mantra to the next level: Instead of writing unique apps for each mobile device or OS, the jQuery mobile framework allows you to design a single highly-branded web site or application that will work on all popular smartphone, tablet, and desktop platforms. Device support

    Easy to use: Try it now!

    jQuery Mobile's emphasis on semantic markup and progressive enhancement makes it super easy to use. If you know basic HTML, you can start building mobile sites right away. Try this cool drag-and-drop UI builder to explore what the library can do, or check out some of the resources below to learn more.

    Demos & documentation Resources: Books, plugins, tutorials

    Powered by Codiqa

    Theming: Built to be branded

    We believe that your web site or app should feel like your brand, not any particular OS. To make building highly customized themes easy, we've created ThemeRoller for Mobile to make it easy to drag and drop colors and download a custom theme. For polished visuals without the bloat, we leverage CSS3 properties like text-shadow, box-shadow, and gradients.

    Get inspired: Built with jQuery Mobile

    There are hundreds of popular web sites and apps built with jQuery Mobile. Here's a small sampling of sites collected on jQM Gallery - be sure to check that site often to see what's new and notable.

    Books & Resources: Read up and learn more

    There is a rich community and ecosystem around jQuery Mobile to help you get up to speed fast. In addition to a wide selection of books, there are Apps & Frameworks, Plugins, Extensions, Tools, Themes, Articles & Tutorials all conveniently collected in the Resources area.

    Master Mobile Web Apps with jQuery Mobile
    by Matt Doyle,
    Elated Books
    jQuery Mobile: Up and Running
    by Maximiliano Firtman,
    O’Reilly Media
    jQuery Mobile
    By Jon Reid,
    O’Reilly Media
    jQuery Mobile First Look
    by Giulio Bai,
    Packt Publishing
    Adobe Dreamweaver CS5.5: Designing and Developing for Mobile with jQuery, HTML5, and CSS3
    by David Powers,
    Adobe Press
    Using the CSS3 Mobile Pack for Adobe Fireworks CS5
    by Jim Babbage,
    Peachpit Press
    Pro jQuery Mobile
    by Brad Broulik,
    Apress
    Sams Teach Yourself jQuery Mobile in 10 Minutes (Sams Teach Yourself — Minutes)
    by Steven E. Holzner,
    Sams

    How to Get Involved

    We welcome input and ideas from the jQuery community through our GitHub repo, blog, forum, and Twitter.

    The jQuery Project is financed entirely by donations and contributions from the jQuery community. Please support the project: Make a donation or contact the project lead, Todd Parker, about corporate sponsorship opportunities.

    qui est sorti en version alpha pendant Paris-Web. C’est très intéressant de voir comment cela s’emboite parfaitement avec l’approche du framework Z présentée ici.

    Il suffit de faire des pages en 3 blocs header, content, footer, d’écrire une fois pour toute la structure de la page, le header/dist, le footer/dist, et il n’y a plus ensuite qu’à enchainer les gabarits de content/.

    Tout cela permettant d’avoir des pages complètes, chargées en ajax sur le mobile, avec des urls permanentes fonctionnelles, et en se concentrant uniquement sur le contenu.

    Je crois que je vais très vite refaire la version mobile de

    http://www.cuisine-libre.fr/

    sur cette base !

  • Le 23 octobre 2010 à 14:46, par Ben S. En réponse à : Un framework HTML est-il possible ?

    Tout d’abord, merci pour cette conférence donnée à Parisweb, synthétique et très claire. Et puis je trouve la démarche et la logique du framework Z très intéressante, inspirante.

    Cela dit je suis un peu dans la même situation que Jacques. Je comprends qu’à une nouvelle page page1.php créée dans le dossier content/, il faille créer également page1.php dans le dossier head/. En revanche, les appels aux js et aux feuilles de style sont bien souvent très similaires d’une page à l’autre. Or, ils sont actuellement placés dans les fichiers du répertoire head/. Donc si je veux par exemple appeler la librairie jquery, je suis obligé de recopier l’appel à la librairie dans tous les fichiers du répertoire.

    Comment t’y prends-tu dans ce cas ? J’aimerais connaître ta position sur ce problème : ferais-tu un répertoire includes/ dans chaque dossier head/, content/, footer/ etc... dans lesquels on placerait les portions de code communes aux fichiers des répertoires correspondants ? Ferais-tu un dossier style/ et js/ au même niveau que les dossiers content, head... (mais le problème se posera probablement pour d’autrs types de codes que des js et du CSS...) ?

  • Le 23 octobre 2010 à 15:16, par Cedric En réponse à : Un framework HTML est-il possible ?

    @Ben S. Merci beaucoup pour ton retour. J’ai eu du mal à trouver le compromis entre synthèse et détail pour ma présentation, cela me fait donc plaisir de savoir que j’y suis parvenu au moins pour quelques auditeurs :)

    Ta question est très bonne, car le <head> pose en effet plusieurs problèmes. Je n’ai volontairement pas fait de choix ni préconisé quoi que ce soit dans le framework Z que j’essaye de garder aussi général que possible pour pouvoir s’appliquer à toutes les situations.

    Néanmoins, je peux te faire un retour d’expérience de ce que je pratique avec, en production, autour de SPIP notamment.

    En ce qui concerne les briques communes qu’on peut réutiliser d’une page à l’autre, comme la partie invariante du <head>, j’ai effectivement opté pour un répertoire inclure/ (include/ pour garder une terminologie anglo-saxonne) unique, commun à tous les blocs.

    Pour le <head>, il y a en plus une partie variante qui concerne le <title>, qui doit arriver en debut de <head> pour des problèmes de référencement, et une partie qui peut varier aussi pour des scripts supplémentaires sur certaines pages.

    La meilleure synthèse que j’ai trouvée est donc d’avoir un bloc head/, suivi d’une inclusion commune include/head, suivi enfin d’un bloc head_js/. Dans la version SPIP du framework, que je suis en train remettre à niveau, cela donne ça :

    http://zone.spip.org/trac/spip-zone/browser/_plugins_/z-core/structure.html

    /_plugins_/z-core/structure.html – SPIP-ZONE

    Revision 58882, 1.9 KB (checked in by rastapopoulos@…, 8 weeks ago)

    Ajout d'une classe générique "composition_macompo" en plus des classes spéficiques à un objet précis (article_macompo, rubrique_macompo, patate_macompo).

    Cela permet alors de styler en une seule fois (et de manière générique *sans savoir à l'avance le type d'objet*) plusieurs objets différents ayant la même composition.

    .composition_macompo balise truc { ... }

    Line 
    1[(#VAL{_Z_DOCTYPE}|defined|?{#VAL{_Z_DOCTYPE}|constant}|sinon{<!DOCTYPE HTML>})][
    2(#SET{class,[page_(#ENV{type-page,page})[ #ENV{type-page,page}_(#ENV{composition,''})]][ composition_(#ENV{composition})]})][
    3(#REM) http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/]
    4<!--[if lt IE 7 ]> <html class="[(#GET{class})][ (#LANG_DIR)][ (#LANG)] no-js ie ie6 lte9 lte8 lte7" xmlns="http://www.w3.org/1999/xhtml" xml:lang="#LANG" lang="#LANG" dir="#LANG_DIR"> <![endif]-->
    5<!--[if IE 7 ]>    <html class="[(#GET{class})][ (#LANG_DIR)][ (#LANG)] no-js ie ie7 lte9 lte8 lte7" xmlns="http://www.w3.org/1999/xhtml" xml:lang="#LANG" lang="#LANG" dir="#LANG_DIR"> <![endif]-->
    6<!--[if IE 8 ]>    <html class="[(#GET{class})][ (#LANG_DIR)][ (#LANG)] no-js ie ie8 lte9 lte8" xmlns="http://www.w3.org/1999/xhtml" xml:lang="#LANG" lang="#LANG" dir="#LANG_DIR"> <![endif]-->
    7<!--[if IE 9 ]>    <html class="[(#GET{class})][ (#LANG_DIR)][ (#LANG)] no-js ie ie9 lte9" xmlns="http://www.w3.org/1999/xhtml" xml:lang="#LANG" lang="#LANG" dir="#LANG_DIR"> <![endif]-->
    8<!--[if (gt IE 9)|!(IE)]><!-->
    9<html class="[(#GET{class})][ (#LANG_DIR)][ (#LANG)] no-js" xmlns="http://www.w3.org/1999/xhtml" xml:lang="#LANG" lang="#LANG" dir="#LANG_DIR">
    10<!--<![endif]-->
    11        <head>
    12                <script type='text/javascript'>/*<![CDATA[*/(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement);/*]]>*/</script>[
    13
    14                (#REM) Debut du head particulier a chaque page
    15                pour inserer un title, des css particulieres(mais surchargees), ou des js *inline*
    16                ]<INCLURE{fond=head/#ENV{type-page},env}>[
    17
    18                (#REM) Partie commune a toutes les pages, sans env
    19                ]<INCLURE{fond=inclure/head}>[
    20
    21                (#REM) Fin du head particulier a chaque page, pour inserer des js specifiques par exemple
    22                pour inserer des js *externes*
    23                ]<INCLURE{fond=head_js/#ENV{type-page},env}>
    24        </head>
    25        <INCLURE{fond=body,env}>
    26</html>

    Si tu penses que ça a un intérêt pédagogique, on peut aussi modifier l’exemple de

    http://github.com/Cerdic/Z/tree/master/php/demo/

    Z/php/demo at master · Cerdic/Z · GitHub

    Format Text

    Headers

    # This is an <h1> tag
    ## This is an <h2> tag
    ###### This is an <h6> tag

    Text styles

    *This text will be italic*
    _This will also be italic_
    **This text will be bold**
    __This will also be bold__
    
    *You **can** combine them*
    

    Lists

    Unordered

    * Item 1
    * Item 2
      * Item 2a
      * Item 2b

    Ordered

    1. Item 1
    2. Item 2
    3. Item 3
       * Item 3a
       * Item 3b

    Miscellaneous

    Images

    ![GitHub Logo](/images/logo.png)
    Format: ![Alt Text](url)
    

    Links

    http://github.com - automatic!
    [GitHub](http://github.com)

    Blockquotes

    As Kanye West said:
    
    > We're living the future so
    > the present is our past.
    

    Code Examples in Markdown

    Syntax highlighting with GFM

    ```javascript
    function fancyAlert(arg) {
      if(arg) {
        $.facebox({div:'#foo'})
      }
    }
    ```

    Or, indent your code 4 spaces

    Here is a Python code example
    without syntax highlighting:
    
        def foo:
          if not bar:
            return true

    Inline code for comments

    I think you should use an
    `<addr>` element here instead.

    car il est vrai que cela touche aussi le fichier page.php

  • Le 23 octobre 2010 à 15:34, par Ben S. En réponse à : Un framework HTML est-il possible ?

    Je crois que je viens de comprendre : je n’avais pas encore regardé le code du framework, mais les commentaires du constructeur semblent répondre à ma question : Il faut, dans mon body, que je créé une instance de la classe Z avec pour paramètre block quelque chose comme array(’content’,’header’,’nav’,’style’,’js’,’footer’,’head’) ;

    je peux ensuite créer un répertoire style/ et js/ au même niveau que content/, head/... avec dans ces nouveaux répertoires un fichier dist.php qui sera utilisé par défaut.

    C’est bien cela ?

  • Le 23 octobre 2010 à 15:36, par Cedric En réponse à : Un framework HTML est-il possible ?

    Oui tout à fait, c’est aussi une possibilité qui fonctionne très bien !

  • Le 24 octobre 2010 à 00:08, par Ben S. En réponse à : Un framework HTML est-il possible ?

    Merci pour ton retour d’expérience, Cédric. Je pense effectivement que ce serait pertinent d’inclure dans l’exemple php cette notion de parties communes/spécifiques du head, car c’est une chose à laquelle on est très vite confronté quand on créé un projet.

    En y réfléchissant bien il me semble que le mieux serait de faire un mixte : utiliser un répertoire style/ et js/ pour conserver une organisation rigoureuse des fichiers, "dans l’esprit" du framework, tout en utilisant un "include" dans les fichiers du head/ permettant de ne pas avoir à dupliquer du code inutilement.

    Reste à savoir où placer le répertoire include/... Par instinct, je pense qu’il vaut mieux créer un répertoire include dans chaque répertoire de bloc (header/, content/, footer/...), ainsi, chaque répertoire include contiendra des fichiers de même "nature" (tous les js dans le dossier js/include/, tous les css communs dans style/include/...)

    En tout cas, je me répète, je trouve cette organisation d’une logique et d’une limpidité étonnante : j’espère pouvoir la mettre en pratique rapidement.

  • Le 25 octobre 2010 à 14:56, par Ben S. En réponse à : Un framework HTML est-il possible ?

    Maintenant qu’il est simple de créer des pages (pour un webmaster), avec ce framework, l’étape suivante concerne le backoffice. En effet, je compte réaliser un petit site vitrine très simple. Les pages n’ont pas vraiment besoin d’être toutes être administrables (ex. Présentation de la société, Nos Valeurs...), mais si elles peuvent l’être, tant mieux ;)

    Je me dis, qu’avec cette séparation du contenu, il devient très simple de réaliser un template d’admin (body-admin.php ?) qui prend en paramètre le nom de la page à éditer (comme le fait l’index.php). Ce template d’admin peut se contenter dans un premier temps de proposer 2 champs :
    - Titre de la page : Créera ou modifiera le fichier correspondant dans le dossier head/) afin d’adapter la balise <title> de la page.
    - Contenu : Propose un éditeur riche de type TinyMCE pour la saisie du contenu de la page.

    Avec ce squelette de page d’admin (et un menu présentant la liste des pages éditables), on pourrait proposer une plateforme d’édition de contenus Wysiwyg très simple et très rapide à mettre en place...

    Qu’en penses-tu, Cédric ?

  • Le 8 décembre 2010 à 06:47, par Eric En réponse à : Un framework HTML est-il possible ?

    Ca fait un moment que je zyeute zpip pour ces raisons. Mais à la longue, je pense à une approche différente : pourquoi pas du XML + XSLT

    On a un fichier
    - module.xml qui liste tout les modules disponibles
    - pages.xml qui déclare toutes les pages du site et les modules qui la composent
    - Une feuille de style XSLT qui génère le HTML correspondant

    Dès que j’ai un temps je me lance. Ca paraît usine à gaz mais sur des gros devs type portail/presse en ligne je pense que c’est rentable

  • Le 13 janvier 2011 à 01:11, par Kaelig En réponse à : Un framework HTML est-il possible ?

    Après avoir trouvé l’approche de Z très intéressantes, je suis tombé sur staticmatic qui permet une intégration très rapide (notamment grâce à haml et scss). Maintenant j’ai du mal à faire machine arrière car c’est vraiment très pratique (mais bien évidemment on s’éloigne du php).

  • Le 14 janvier 2011 à 10:06, par jpvincent En réponse à : Un framework HTML est-il possible ?

    j’avais implémenté la même idée à une époque où ce genre de framework n’existait pas, du coup j’ai fait des choix très différents, qui peuvent peut être t’inspirer ? :
    - chaque module est une classe héritant de la même classe, et généralement divisée en 2 méthodes, l’une qui calcule les données , l’autre qui prend les données et va générer du HTML (à partir de templates)
    - comme toi, chaque module est appellable dans un layout générique ou en standalone pour l’AJAX.
    - en plus, pour chaque module on peut appeller uniquement la partie data, formatable en JSON ou XML, ce qui crée une API à pas cher, utilisable en interne ou par des tiers
    - il y a des scripts PHP libres (non mis dans des classes) qui représentent les pages et qui exécute les modules pour les placer dans le layout
    - le routage vers les pages ou les modules n’est pas automatique, c’est un fichier d’expressions régulières qui correspond chacune à une page ou un module. Ca permet d’être libre dans le format de ses urls

    ce que je regrette de ne pas avoir fait : je n’ai pas formalisé les dépendances JS et CSS de chaque module, ce qui est dommage car lorsque le site grossit, ça permettrait aux pages de n’envoyer que les bonnes dépendances

    dernière chose : le titre de ta présentation laissait penser qu’on pouvait faire quelque chose pour éviter les gros copier/coller de HTML entre chaque projet, mais comme moi c’est une question d’organisation du code plutôt que de framework

  • Le 14 janvier 2011 à 11:11, par Kaelig En réponse à : Un framework HTML est-il possible ?

    Et hop un petit lien vers la vidéo de la conf :

    http://dai.ly/fEbA0E
  • Le 5 février 2011 à 00:55, par rivsc En réponse à : Un framework HTML est-il possible ?

    Je viens de regarder la conf, super intéressant et bien présenté ! Je partage un peu l’avis du développeur qui a parlé de rails.

    Effectivement on a cette notion de vues et de controlleurs mais chaque vue est une page (le content particulier qui fait qu’il y a lieu d’avoir une page) pour le reste (les portlets, les zones ou boites html que l’on retrouve sur plusieurs pages) il existe dans le framework les partials ce sont des morceaux de vues qui peuvent être inclue dans n’importe quelle page.

    La gestion des layouts existe aussi. La seul chose qui diffère vraiment c’est la structure des répertoires et des partials qui n’est pas normalisée par rails. Le fait aussi que ce soit le framework serveur qui gère tout ça va effectivement à l’encontre d’un framework html. Sinon petite suggestion pour être langage serveur agnostique : mettre une balise commentaire html normalisée qui fait l’inclusion :

    Il suffira alors de passer le répertoire parent pour "compiler" chaque page dans le cas de la soutraitance de l’intégration et d’adapter dans chaque langage serveur "l’inclusion html" en "inclusion serveur".

  • Le 7 février 2011 à 09:31, par Kaelig En réponse à : Un framework HTML est-il possible ?

    Je viens de tomber là dessus :

    http://nanoc.stoneship.org/docs/3-getting-started/

    nanoc › Getting Started

    Requirements

    This tutorial does not cover the installation of nanoc. For information on how to install nanoc, as well as Ruby and Rubygems, check out the Installation page.

    This tutorial requires kramdown. Kramdown is a Ruby implementation of Markdown, which allows you to write HTML in a easy-to-use plain text format. If you haven’t used Markdown before, don’t fear—it’s quite easy to use. To install kramdown, jump to your terminal and type:

    % gem install kramdown

    You should also install adsf, a tool that allows you to fire up a web server in any directory, which is very useful for previewing compiled nanoc sites. nanoc’s view command, used in this tutorial, requires adsf to be installed. Install adsf like this:

    % gem install adsf

    Be sure to install adsf, not asdf. No, that’s not a tyop!

    nanoc also requires a basic level of experience with Ruby. It is possible to use nanoc with no Ruby knowledge, but to take full advantage of nanoc, you’ll need to know Ruby well. I recommend the Programming Ruby book to people who don’t have a lot of Ruby experience yet.

    Creating a Site

    nanoc is a command-line application. This means that in order to use nanoc, you have to type geeky commands into a terminal all day. Hey, that’s the way all cool apps work.

    A nanoc-powered site is a directory with a specific structure. In this tutorial, we’ll create a site named tutorial. To create this site, type into the terminal:

    % nanoc create_site tutorial

    If you did that right, you should see something like this in the terminal:

    % nanoc create_site tutorial
          create  config.yaml
          create  Rakefile
          create  Rules
          create  content/index.html
          create  content/stylesheet.css
          create  layouts/default.html
    Created a blank nanoc site at ‘tutorial’. Enjoy!
    % 

    The nanoc-powered site named tutorial has now been created. Go into the directory and list the files there. You should see something like this:

    % cd tutorial
    tutorial% ls -l
    total 24
    -rw-r–r–  1 ddfreyne  staff   22 Feb 17 14:44 Rakefile
    -rw-r–r–  1 ddfreyne  staff  692 Feb 17 14:44 Rules
    -rw-r–r–  1 ddfreyne  staff  100 Feb 17 14:44 config.yaml
    drwxr-xr-x  4 ddfreyne  staff  136 Feb 17 14:44 content
    drwxr-xr-x  3 ddfreyne  staff  102 Feb 17 14:44 layouts
    drwxr-xr-x  3 ddfreyne  staff  102 Feb 17 14:44 lib
    drwxr-xr-x  2 ddfreyne  staff   68 Feb 17 14:44 output
    tutorial% 

    What all those files and directories are for will all become clear soon.

    Compiling the Site

    Before doing anything else, make sure the current working directory is the site you just created. All nanoc commands, except for create_site, require the current working directory to be a nanoc site. So, if you haven’t done it before:

    % cd tutorial
    tutorial%

    Every new nanoc site already has a bit of content. It comes with one simple page with some simple “getting started” instructions. Before you can view the site, it needs to be compiled. To compile the site, do this:

    tutorial% nanoc compile

    Or, if you want it short, just type nanoc:

    tutorial% nanoc

    This is what’ll appear in the terminal while nanoc is compiling:

    tutorial% nanoc compile
    Loading site data…
    Compiling site…
          create  [0.01s] output/index.html
    
    Site compiled in 0.01s.
    tutorial% 

    A file named index.html has been created in the output directory. Start a web server using the view command, like this:

    tutorial% nanoc view

    Now, open your web browser and navigate to http://localhost:3000/. What you’ll see is something like this:

    (If you open the index.html directly in your web browser, the stylesheet will most likely not be loaded. This is because the page has an absolute link to the style.css file, not a relative one.)

    You can also open the output/index.html file in your favourite text editor, where you’ll find that the file is just a normal HTML page.

    Editing the Home Page

    The first step in getting to know how nanoc really works will involve editing the content of the home page. First, though, a quick explanation of how uncompiled pages are stored.

    The pages in a nanoc site are stored in the content directory. Currently, that directory has only two files: index.html and stylesheet.css. The first file forms the home page, while the second file is the stylesheet. If you open the index.html file, you’ll notice a section containing metadata in YAML format at the top.

    Let’s change the content of the home page. Open index.html and add a paragraph somewhere in the file. I recommend something like this:

    <p>This is a brand new paragraph which I've just inserted into this file! Gosh, I can barely control my excitement!</p>

    To view the changes, the site must be recompiled first. So, run the compile command. You should see something like this:

    tutorial% nanoc compile
    Loading site data…
    Compiling site…
          update  [0.01s] output/index.html
    
    Site compiled in 0.01s.
    tutorial% 

    The number between brackets next to the output/index.html filename indicates the time it took for nanoc to compile the home page. At the bottom, the total time needed for compiling the entire site is also shown.

    Make sure that the preview server (nanoc view) is still running, reload http://localhost:3000/ in your browser, and verify that the page has indeed been updated.

    In the same file, let’s change the page title from “Home” to something more interesting. Change the line that reads title: "Home" to something else. The file should now start with this:

    --- 
    title: "My New Home Page"
    ---

    The metadata section at the top of the file is formatted as YAML. All attributes are free-form; you can put anything you want in the attributes: the page title, keywords relevant to this page, the name of the page’s author, the language the page is written in, etc.

    Recompile the site and once again load http://localhost:3000/ in your browser. You will see that the browser’s title bar displays the page’s title now. If you’re wondering how exactly nanoc knew that it had to update the stuff between the <title> and </title> tags: don’t worry. There’s no magic involved. It’ll all become crystal clear in a minute. (Take a peek at layouts/default.html if you’re curious.)

    Adding a Page

    In nanoc, pages are sometimes referred to as “items.” This is because items don’t necessarily have to be pages: JavaScript and CSS files aren’t pages, but they are items.

    To create a new page or item in the site, use the create_item command (or ci for short). Let’s create an “about” page like this:

    tutorial% nanoc create_item about

    You should see this:

    tutorial% nanoc create_item about
          create  content/about.html
    tutorial% 

    Open the newly generated file and put some text in it, like this (be sure to leave the metadata section intact):

    <h1>My cute little "About" page</h1>
    
    <p>This is the about page for my new nanoc site.</p>

    In the metadata section, change the title to something else:

    title: "My Cool About Page"

    Recompile the site, and notice that a file output/about/index.html has been created. With the preview server running, open http://localhost:3000/about/ in your browser and admire your brand new about page. Shiny!

    By the way, if you don’t like having a metadata section at the top of every page (perhaps because it breaks syntax highlighting), you can put the metadata in a YAML file with the same name as the page itself. For example, the content/about.html page could have its metadata stored in content/about.yaml instead.

    Customizing the Layout

    The default home page recommended editing the default layout, so let’s see what we can do there.

    As you probably have noticed already, the page’s content files are not complete HTML files—they are partial HTML files. A page needs <html>, <head>, <body>, … elements before it’s valid HTML. This doesn’t mean you’ve been writing invalid HTML all along, though, because nanoc layouts each page as a part of the compilation process.

    Take a look at the default.html file in the layouts directory. Just like items, it contains a metadata section at the top of the file. Open it in your text editor. It almost looks like a HTML page, with the exception of this piece of code:

    <div id="main">
      <%= yield %>
    </div>

    The odd construct in the middle of that piece of code is an embedded Ruby instruction. The <%= yield %> instruction will be replaced with the item’s compiled content when compiling.

    If you are not familiar with embedded Ruby (also known as eRuby), take a look at the eRuby article on Wikipedia, or the Embedding Ruby in HTML section of the Ruby and the Web chapter of the online Programming Ruby book.

    The is another important piece of embedded Ruby code near the top of the file:

    <title>A Brand New nanoc Site - <%= @item[:title] %></title>

    This is where the page’s title is put into the compiled document.

    Every page can have arbitrary metadata associated with it. To demonstrate this, add the following line to the metadata section of the about page:

    author: "John Doe"

    Now output the author name in the layout. Put this piece of code somewhere in your layout (somewhere between the <body> and </body> tags, please, or you won’t see a thing):

    <% if @item[:author] %>
      <p>This page was written by <%= @item[:author] %>.</p>
    <% end %>

    Recompile the site, and load http://localhost:3000/about/ in your browser. You’ll see that the about page has a line saying This page was written by John Doe, while the home page does not—as expected!

    Writing Pages in Markdown

    You don’t have to write pages in HTML. Sometimes, it is easier to use another language which can be converted to HTML instead. In this example, we’ll use Markdown to avoid having to write HTML. nanoc calls these text transformations filters.

    Get rid of the content of the home page (content/index.html) and replace it with the following Markdown-formatted text (but leave the metadata section intact):

    A First Level Header
    ====================
    
    A Second Level Header
    ---------------------
    
    Now is the time for all good men to come to
    the aid of their country. This is just a
    regular paragraph.
    
    The quick brown fox jumped over the lazy
    dog's back.
    
    ### Header 3
    
    > This is a blockquote.
    > 
    > This is the second paragraph in the blockquote.
    >
    > ## This is an H2 in a blockquote

    To tell nanoc to format the home page as Markdown, let nanoc run it through the kramdown filter. For this, the Rules file is used. This file specifies all processing instructions for all items. It consists of a series of rules, which in turn consist of three parts:

    rule type
    This can be compile (which specifies the filters and layouts to apply), route (which specifies where a compiled page should be written to) or layout (which specifies the filter to use for a given layout).
    selector
    This determines what items or layouts the rule applies to. It can contain the * wildcard, which matches anything. The default rules file has three rules of each type, and they all apply to all items or layouts.
    instructions
    This is the code inside the do…end block and specifies what exactly should be done with the items that match this rule.

    These rules are quite powerful and are not fully explained in this tutorial. I recommend checking out the manual for a more in-depth explanation of the rules file.

    Take a look at the default compilation rule (the compile '*' do … end one). This rule applies to all items due to the * wildcard. When this rule is applied to an item, the item will first be filtered through the erb filter and will then be laid out using the default layout.

    To make sure that the home page (but not any other page) is run through the kramdown filter, add this piece of code before the existing compilation rule:.

    compile '/' do
      filter :kramdown
      layout 'default'
    end

    It is important that this rule comes before the existing one (compile '*' do … end). When compiling a page, nanoc will use the first and only the first matching rule; if the new compilation rule were below the existing one, it would never have been used.

    Now that we’ve told nanoc to filter this page using kramdown, let’s recompile the site. The output/index.html page source should now contain this text (header and footer omited):

    <h1>A First Level Header</h1>
    
    <h2>A Second Level Header</h2>
    
    <p>Now is the time for all good men to come to
    the aid of their country. This is just a
    regular paragraph.</p>
    
    <p>The quick brown fox jumped over the lazy
    dog's back.</p>
    
    <h3>Header 3</h3>
    
    <blockquote>
        <p>This is a blockquote.</p>
    
        <p>This is the second paragraph in the blockquote.</p>
    
        <h2>This is an H2 in a blockquote</h2>
    </blockquote>

    The kramdown filter is not the only filter you can use—take a look a the full list of filters included with nanoc. You can also write your own filters—read the Writing Filters section in the manual for details.

    Writing some Custom Code

    There is a directory named lib in your nanoc site. In there, you can throw Ruby source files, and they’ll be read and executed before the site is compiled. This is therefore the ideal place to define helper methods.

    As an example, let’s add some tags to a few pages, and then let them be displayed in a clean way using a few lines of custom code. Start off by giving the “about” page some tags. Open about.html and add this to the meta section:

    tags:
      - foo
      - bar
      - baz

    Next, create a file named tags.rb in the lib directory (the filename doesn’t really matter). In there, put the following function:

    def tags
      if @item[:tags].nil?
        '(none)'
      else
        @item[:tags].join(', ')
      end
    end

    This function will take the current page’s tags and return a comma-separated list of tags. If there are no tags, it returns “(none)”. To put this piece of code to use, open the default layout and add this line right above the <%= yield %> line:

    <p>Tags: <%= tags %></p>

    Recompile the site, and take a look at both HTML files in the output directory. If all went well, you should see a list of tags right above the page content.

    Writing your own functions for handling tags is not really necessary, though, as nanoc comes with a tagging helper by default. To enable this tagging helper, first delete tags.rb and create a helper.rb file (again, the filename doesn’t really matter) and put this inside:

    include Nanoc::Helpers::Tagging

    This will make all functions defined in the Nanoc::Helpers::Tagging module available for use. You can check out the API documentation for the Tagging helper, but there is only one function we’ll use: tags_for. It’s very similar to the tags function we wrote before. Update the layout with this:

    <p>Tags: <%= tags_for(@item) %></p>

    Now compile the site again, and you’ll see that nanoc shows the tags for the page, but this time using the built-in tagging helper.

    nanoc comes with quite a few useful helpers. The API documentation describes each one of them.

    That’s it!

    This is the end of the tutorial. I hope that this tutorial both whet your appetite, and gave you enough information to get started with nanoc.

    There’s more reading material. It’s definitely worth checking out the following chapters; they’re rather big, but they contains everything you need to know about nanoc.

    Ce n’est pas un "framework html", mais quelque chose qui facilite l’intégration de sites statiques.

    À tester, donc.

Répondre à cet article

Qui êtes-vous ?

Pour afficher votre trombine avec votre message, enregistrez-la d'abord sur gravatar.com (gratuit et indolore) et n'oubliez pas d'indiquer votre adresse e-mail ici.

Ajoutez votre commentaire ici
  • Ce formulaire accepte les raccourcis SPIP [->url] {{gras}} {italique} <quote> <code> et le code HTML <q> <del> <ins>. Pour créer des paragraphes, laissez simplement des lignes vides.