By Ingeniweb. A Django site.
Mars 4, 2010
» Resizing and cropping thumbnails with jquery

Resizing and cropping images with jquery

Sometimes, we need images with fixed dimensions (carousels, photo albums …), but all images don’t have the good dimensions or good ratio height /width.

This little jquery script will help you for this usecase.

In this example we will fix the dimension and position of thumbnails placed in blocks using the class « imageContainer ». « imageContainer » have a fixed width and height (in this example 250px/150px). The size of thumbs will be increased or reduced, and the thumb will be moved inside its container to get a centered cropping. Of course images and its containers must have a relative position.

Your html template code looks like :

  <a class="imageContainer" href="the_link">
    <img src="the_image_src" alt="" width="450" height="300" />
  </a>
  <a class="imageContainer" href="another_link">
    <img src="another_image_src" alt="" width="200" height="100" />
  </a>

In your css, you must fix at least :

.imageContainer,
.imageContainer img {
  position: relative;
}

.imageContainer {
  width: 250px;
  height: 150px;
  overflow: hidden;
  border: 1px solid grey;
}

The javascript code is simple :

var canImproveResolution = false;

thumbResize = function(thumb, min_width, min_height, orientation) {
    twidth = jQuery(thumb).width();
    theight = jQuery(thumb).height();
    new_height = theight;
    new_width = twidth;
    // strange 1px bug on MSIE
    if (jQuery.browser.msie) {
        min_width = min_width+1;
        min_height = min_height+1;
    }
    //calculate the good size
    if (orientation=='landscape') {
        ratio = min_width/min_height;
        tratio = twidth/theight;
        if (tratio>ratio) {
            new_height = min_height;
            new_width = parseInt(new_height*tratio);
        }
        else {
            new_width = min_width;
            new_height = parseInt(new_width/tratio);
        }
    }
    else {
        ratio = min_height/min_width;
        tratio = theight/twidth;
        if (tratio>ratio) {
            new_width = min_width;
            new_height = parseInt(new_width*tratio);
        }
        else {
            new_height = min_height;
            new_width = parseInt(new_height/tratio);
        }
    }

    // resize thumb
    if (theight!=new_height || twidth!=new_width) {
        jQuery(thumb).height(new_height);
        jQuery(thumb).width(new_width);
    }
    // adjust position (vertical and horizontal centering for css cropping)
    if (new_width > min_width) {
        moveleft = parseInt((new_width-min_width)/2);
        jQuery(thumb).css('left', '-'+moveleft+'px');
    }
    if (new_height > min_height) {
        movetop = parseInt((new_height-min_height)/2);
        jQuery(thumb).css('top', '-'+movetop+'px');
    }
    // improve resolution
    if (canImproveResolution && (new_width > twidth || new_height > theight)) improveResolution(thumb);
}

resizeThumbs = function(thumbs, min_width, min_height) {
    orientation = (min_height > min_width) ? 'portrait' : 'landscape';
    // hide images before resizing to avoid bad visual effect
    thumbs.each( function() {
            jQuery(this).css('visibility', 'hidden');
        })
    // use window.load because on document.ready images are not always loaded
    jQuery(window).load(function() {
        thumbs.each( function() {
            thumbResize(this, min_width, min_height, orientation );
            jQuery(this).css('visibility', 'visible');
        })
    });
}

// change image src for a better resolution
// this is just an example for Plone, adapt it with
// your own sizes rules

improveResolution = function(img) {
    img_src = img.src;
    img_src = img_src.replace(/\/image_preview/gi, '/image');
    img_src = img_src.replace(/\/image_mini/gi, '/image_preview');
    img_src = img_src.replace(/\/image_thumb/gi, '/image_mini');
    img.src = img_src;
}

For Plone users, there is a small improvement, if you fix the variable :

canImproveResolution = true;

you will get a better resolution when increasing image size  (works only with standard plone image thumb sizes …).

At last launch the script for the wanted thumbnails :

jQuery(document).ready(function(){
  resizeThumbs(jQuery('.imageContainer img'), 250, 150)});

Février 6, 2010
» Plone and multilingual sites

Usually we build multilingual Plone sites with LinguaPlone.

This solution has a big advantage, it’s generic and very easy to implement in a plone site.

But there are many inconvenients, due to the design of this product (translations are independent by design) :

  • Each translation is a new Archetype object, and it could be a big problem on sites with many contents, the portal objects number is increased by the number of available languages.
  • Translations uses plone references catalog to be linked to the original (called canonical) object, but when moving objects translations are not moved, when copying pasting objects, translations are not pasted, when deleting objects translations are not deleted, when reordering contents, translations are not reordered, when publishing objects translations are not published, … For web masters maintaining a site  with LinguaPlone inside could be a challenge.
  • When translating folders with LP, all translated contents are moved from the canonical folder to the translated folder with same language, translating low level folders on big depth tree sites could take a long long time, don’t be surprise if you get errors.
  • If a content is neutral (with no language attribute), inside a translated folder, it could not be seen when browsing a translation of the parent folder.
  • At last a lower problem :  the translation edit forms are not pretty to use, they show a table with two columns, the first column with the « canonical » content inside in « view » mode, the second column with the translation edit form, in fixed width sites the translated form width is sometimes ridiculously small.

But since many years we use LinguaPlone because it was the only easy way to make multilingual Plone sites.

By the past we were using a LP patch called LinguaFace to reduce the number of problems with LP (synchronisation on reorder, copy-paste, delete, or move – see neutral contents inside all translated folders – more usable translation edit forms …), but LF add a new layer of complexity and maintaining it with all LP versions becomes complicated. See some examples on how it works :

  • when a content is copied, all translations are copied
  • when a content is pasted or moved all translations are pasted or moved at the good place (not so easy)
  • when a content is published or retracted translations follow the same workflow transition
  • when a folder is translated, we don’t see only objects inside but also objects with same canonical Path (a new catalog index) to see also neutral contents.
  • Navtree is patched, breadcrumbs are patched, to use canonical path
  • and so on …

A big nightmare.

To day a new solution exists that store translations inside each Archetypes field, raptus.multilingualfields, and a Plone integration of raptus.multilanguagefields called raptus.multilingualplone that extends the schema of all Plone Content Types making them translatable. raptus.multilingualfields also provides multilingual catalog indexes that return the good translated data when searching for contents or displaying trees, and multilingual criterions for topics.

A LP feature not provided by raptus.multilingualfields is the internationalization of urls, if you really need this feature, i think it’s not a big challenge to add some traversal rules, for me it’s not essential.

AnotherLP  feature that can’t be provided when storing translations in fields is to get different workflows or security settings for each translation. If you need this feature use LinguaPlone, LinguaPlone is done for that, it makes all translated contents independent, but i’m curious to know the number of users who really want this feature, all clients i had never ask for that but finally, after some LP experience, always wanted the exact opposite use-case.

To make your Plone site translatable with raptus.multilanguagefields, you have two choices :

  1. Add raptus.multilanguageplone in your buildout and install it in your Plone Site using extensions products control panel, to make all your Plone content types and derived translatable (all fields for which translation make a sense are translatable).
  2. I prefer integrate by myself raptus.multilanguagefields inside a product, since we could want just some fields or content types translatable, as example i don’t need to translate the images or the files contents, just their titles and descriptions.

How to implement the second solution ?

Just take a look at raptus.multilanguageplone code, it’s easy :

  1. Make your archetype extenders to make your wanted fields translatable, example can be found here
  2. register your extenders in setuphandlers (Generic Setup import step), example here
  3. replace the standard catalog  indexes with multilingual indexes in Generic Setup profile, example here

That’s all, you will get superb edit forms with translatable fields inside, you also will get a google help to translate contents (a pleasant gadget). I say « Bravo » to raptus developpers.

Important :

  • these products are young, and there’s still many work todo to make it work without problems (tests are needed …). Last 0.6 releases have bugs under plone3.3, use the svn versions below instead.
  • raptus.multilanguageplone 0.6  has a bug in extenders with primary fields, tested in Plone 3.3  (fixed in branch aws_evols, not tested with images at this time)
  • raptus.multilanguagefields 0.6 has a bug, doctests are broken in Plone3.3 (fixed in trunk )
  • At this time these products don’t have unit tests or functional tests, it’s the only reproach i can make.  I started the work  here, and here

Décembre 23, 2009
» Migrer vos vieux sites vers Plone 3 ou Plone 4


Vous êtes nombreux à avoir ce souci, et c’est pareil pour moi, de migrer vos anciens sites CPS ou Plone2 vers une technologie plus mature et plus pérenne, à savoir Plone3 ou Plone4.

Ce billet n’a pas la prétention de résoudre ces questions avec un framework sophistiqué et néanmoins intéressant appelé Products.contentmigration mais plus humblement de vous donner quelques astuces bien pratiques.

Par exemple vous ne savez pas comment supprimer ces maudites Access Rules, qui, c’est pas faute de vous avoir prévenu étaient dangereuses, alors c’est facile, vous avez besoin d’un petit import :

from ZPublisher.BeforeTraverse import unregisterBeforeTraverse

et sur chaque objet migré :

rules = unregisterBeforeTraverse(obj, 'AccessRule')
if rules:
     try: del getattr(obj, rules[0].name).icon
     except: pass

Passons à une chose stupide mais lourde de conséquences, lorsque vous migrez des contenus d’un meta_type vers un autre, la plupart du temps il faut copier-coller l’objet et lui ré-attribuer tous ses anciens attributs, mais supposons que l’objet est structurellement le même ou presque, pourquoi s’embêter (imaginez dans le cas d’un dossier à la racine d’un site comme ça peut faire mal), il suffit de :

obj.__class__ = new_class

vous êtes assez malins pour trouver new_class et new_portal_type…

et dans le cas d’un Archetypes object à l’arrivée

obj.updateSchema()

C’est un exemple à ne pas suivre, mais comme tous les exemples de ce type il est bien pratique (ça se compte en jours/semaines de prise de tête en moins)

Sans doute qu’il y aura une suite à ce ticket.

Août 1, 2009
» The power of Deliverance and PyQuery

Some times ago i made a new skin for the French-speaking PYthon Association (AFPY) web site, using Deliverance and PyQuery. I made this exercice on my free time with many pleasure.

You can see the Deliverance power here :

- The home page without Deliverance, the same using Deliverance proxy : all dynamic contents are taken from original Plone site, try to find it, you will notice the Deliverance + PyQuery magic in action :-)

- The association pages without Deliverance (a sphinx site), the same contents injected in the site with Deliverance

Thanks to Gaël Pasgrimaud, a friend of mine and coworker, for his big work which really help me :

Here, we use a specific Gael’s buildout and a specific package done for our Deliverance projects used at Ingeniweb, our company. With these tools (if some people are interested in, it could be released on pypi, tell us …), we get the best flexibility for Deliverance :

  • PyQuery integration
  • The good base rules for Deliverance to avoid theming bugs with Ajax and HTML editor (*)
  • Dynamic css : css are mako templates served by a skin server, colors fonts and other properties are set in a « .ini » file
  • A base mako css for Plone which permits to start the work of externalize the entire css :
    in our projects, all portal_css content links from Plone are stripped when the Plone site is called through Deliverance (just add a condition for Plone stylesheets in portal_css : python:request.HTTP_HOST in request.SERVER_URL), the final css is lighter, the Deliverance css is really clean without many ‘!important’ bad overloads)
  • Supervisor deamon to control skin servers
  • We can use eggs for our Deliverance skins.

(*) to get real wysiwyg rendering in Plone behind Deliverance ‘s  HTML editor areas, use also FCKeditor.Plone 2.6.4, in FCKeditor control panel you will find the way to inject Deliverance css in wysiwyg area, it’s an important feature for end users.

Now i can take my summer holidays in peace with myself :-)


Mai 23, 2009
» Some Deliverance tips

I really like to use Deliverance for skinning Plone or any web application. In this post, i just want to help Deliverance beginners to configure their server, and to talk about PyQuery, which could be a good Deliverance companion.

Apache 2.2 + Deliverance : configuration

I spent some time to configure Apache in front of Deliverance, you will find here a possible configuration.

Deliverance Server configuration :

In your rules.xml, the first declaration relates to server config, use ’0.0.0.0′  as server address to be able to serve any ip address :

<server-settings>
 <server>0.0.0.0:8000</server>
 <execute-pyref>true</execute-pyref>
 <display-local-files>false</display-local-files>
 <dev-allow>
 localhost
 </dev-allow>
 <dev-user username="dev" password="dev" />
 <dev-expiration>60</dev-expiration>
</server-settings>

Always in rules.xml you need to write the proxy rule for Zope Virtual Host or another server.

If you want to serve a plone site located at http://localhost:8080/myplonesite :

<proxy path="/" rewrite-links="1">
     <dest href="http://localhost:8080/VirtualHostBase/http/{SERVER_NAME}:8000/myplonesite/VirtualHostRoot" />
</proxy>

If you need a more complex configuration in front of Zope, you can always use Apache + Varnish or SQUID + Pound, or IIS + EEP, and ZEO in front of Zope using another port (90 in this example) and use this Deliverance proxy rule :

<proxy path="/ rewrite-links="1">
    <dest href="http://{SERVER_NAME}:90" />
</proxy>

And if you want to serve anything else for another path :

<proxy path="/anotherpath" rewrite-links="1">
    <dest href="http://anythingelse" />
</proxy>

Apache VirtualHost configuration

You can use Deliverance on port 80 (just replace 8000 by 80 in rules.xml) to directly serve your site, but you would prefer Apache for that in many cases.

Suppose you want to rewrite all requests to « www.mysite.org » with a Deliverance response (on www.mysite.org:8000), you can use the mod_rewrite like this :

<VirtualHost *:80>
    ServerName www.mysite.org
    ServerAlias mysite.org
    ErrorLog "logs/error.mysite.org.log"
    CustomLog "logs/access.mysite.org.log" combined

    # do not forget this declaration
    ProxyPreserveHost On
    RewriteEngine On
    RewriteLog "logs/rewrite.mysite.org.log"
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule ^/(.*) http://%{SERVER_NAME}:8000/$1 [P]

    # etc ...

</VirtualHost>

That’s all.

If you want to serve urls starting with a particular path (/mypath),  just change your rewrite rule like this :

    RewriteRule ^/mypath(.*) http://%{SERVER_NAME}:8000/_vh_mypath$1 [P]

Just take care in this last case to put the good urls in your Deliverance static contents, if you need it .

In fact you can do anything you want with rewrite rules :-)

Deliverance and PyQuery

PyQuery is a jQuery-like library for Python which help you to play easily with html elements. Combined with Deliverance you will be able, with a python rule, to modify content or theme on the fly, at any point of your Deliverance transformation.

To learn how to add PyQuery rules to Deliverance, read this post  (many thanks to Gaël who help me to learn Deliverance) :
http://www.gawel.org/weblog/en/2008/12/skinning-with-pyquery-and-deliverance

Read also  :
http://www.openplans.org/projects/deliverance/lists/deliverance-discussion/archive/2008/12/1229591136002/forum_view

And now just try these example :

You have a floating right toolbar with floating right tabs inside in your html template theme :

<ul id="right-bar">
    <li><a href="/abcd">ABCD</a></li>
    <li><a href="/efgh">EFGH</a></li>
</ul>

You have a floating left toolbar with floating left tabs inside in your html source content :

<ul id="left-bar">
    <li><a href="/abcd">ABCD</a></li>
    <li><a href="/efgh">EFGH</a></li>
</ul>

With Deliverance xml rules you want to replace right tabs by left tabs like this :

    <replace content="children:#left-bar" theme="children:#righ-bar" />

But of course you need to reverse tabs order before or after xml transformation.
To modify the theme  just add a pyquery rule after the replace declaration :

    <pyquery pyref="myskinproduct.rules:pqrules" />

In your rules.py,  create your pqrules function like this :

def pqrules(content, theme, resource_fetcher, log) :

    # if you prefer to work on content
    # before Deliverance transform
    # replace theme('#right-bar') by content('#left-bar')
    nav = theme('#right-bar')
    navitems = nav('li')
    navitems.reverse()
    # i'm not sure that it's needed :
    nav.empty()
    nav.append(navitems)

Other examples :

    # replace a search button text with 'OK' in content
    content('#portal-searchbox .searchButton').val('OK')

    # remove icons from a navigation portlet
    # replace icons by "> "
    nav = content('#navigation')
    navitems = nav('li')
    navitems('img').remove()
    navitems.append('<span>&gt;&nbsp;</span>')

    # add a "last-item" class to last tab in a toolbar
    from pyquery import PyQuery as pq
    navitems = content('#navbar li')
    if navitems :
        pq(navitems[len(navitems-1)]).addClass('last-item')

    # if you have inserted external contents in content area with Deliverance xml rules
    # you want to change a navitem class in result
    if theme("#photos') :
        selectNavigationItem('#photos')

    #etc ...

To do this kind of template manipulations, changing content on source application could be a best practice, it depends of  your particular situation.
But i’m sure that it’s a fast way  ;-)

The problem is how to test the result ? twill could be a solution …

Do not transform some contents with deliverance

If you dont like bad surprises, you need to abort ajax html content transformation. And in some other cases you need also to abort Deliverance transformation (see example)

In your rules.xml, just add :

    <match pyref="myproduct.rules:match_notheme" abort="1" />

and in your rules.py

def match_notheme(req, resp, headers, *args):

    match = False
    if req.headers.get('X-Requested-With', '').startswith('XML'):
        match = True
    # the html template of FCKEditor iframe must be unchanged
    if req.path_info.startswith('/editor'):    
        match = True
    if 'notheme' in req.GET:
        match = True
    return match

Novembre 27, 2008
» Styliser plone3 : quelques trucs sortis du grenier de ma grand-mère.

For beginner piano …

Dans cet article nous trouverez quelques conseils pour créer son produit de thème pour Plone3 à partir d’une maquette fournie par un graphiste.  Il évoluera dans le temps car j’y ajouterai quelques notes de travail au fure et à mesure que de nouvelles idées viennent, c’est pas tous les jours :-) .  Nous n’aborderons pas les styles dynamiques (utilisation de collective phantasy par exemple) ni l’utilisation de delivrance (on garde ça pour nos expériences futures, car même si c’est alléchant, ce n’est pas encore facile à installer et on ne peut pas tout faire avec).

Cet article n’aborde pas ou alors seulement si c’est nécessaire les questions techniques (créer son produit de thème avec paster, utilisation du buildout), vous trouverez ces explications là sur bien d’autres sites.

Les conseils que l’on peut donner dés le départ sont :

  • Rester simple.
  • Garder l’oeil ouvert : ce qui est important peut vous échapper
  • Essayer d’utiliser au maximum les templates de Plone par défaut
  • Ne pas overloader les styles de Plone par défaut mais plutôt réécrire les styles de Plone que vous voulez changer voire même repartir de zéro sauf si les modifications à faire sont simples ou si vous maîtrisez bien le langage css.
  • Eviter les hacks css au maximum.

I. Rester simple

C’est simple à dire mais c’est sans aucun doute le plus difficile à faire. On pourrait écrire plusieurs tomes sur ce sujet et je vous conseille fortement de visiter les sites dédiés à l’intégration graphique d’un site web.

Pour rester simple il faut d’abord que les documents décrivant la charte graphique soient à la fois simples et complets, à savoir que le(a) graphiste doit vous donner au minimum un exemple de page intérieure du site qui permettra de ne pas se tromper sur la typographie des différentes parties du site. Il faut également que cette charte graphique corresponde aux cas d’utilisation, et qu’il n’y ait pas des éléments susceptibles de vous égarer, ou des éléments non décrits :

  • Si le site a parfois 3 colonnes avec une colonne à gauche et à droite, la présentation de ces colonnes et des boîtes qu’elles contiennent doit être fournie dans la maquette.
  • La typographie doit être suffisamment exhaustive : paragraphes et plusieurs niveaux de titres, couleur et autres effets typographiques sur les liens, par exemple
  • le(a) graphiste doit fournir un fichier où on peut voir quelles polices sont utilisées (un JPEG ou un PDF est sujet à caution, demandez un format Photoshop pour la maquette)

A partir de là, l’intégrateur doit rester simple et éviter ce genre de choses :

  • Ajouter des styles quand il n’en faut pas : on voit ça trop souvent. Pour la typo globale, il suffit de redéfinir les styles des balises html de base (p, h1, h2, h3 …) >  styles décris dans Plone par la feuille de styles base.css.dtml qu’il faudra réécrire si on choisit de ne pas overloader les styles.
    D’autre part du point de vue accessibilité et respect des normes un titre s’écrit <hx>My title</hx> et non pas <p class= »titlex »>My title</p>. Attention, accessibilité ne veut pas dire uniquement que votre site doit rester lisible par un appareil lisant le braille, ça veut dire aussi qu’il sera conforme à ce qu’on attend, et si par exemple dans le futur vous devez importer vos pages statiques vers une techno dynamique ce sera beaucoup plus simple si vous avez respecté les normes.
    Si sur certains templates les styles des titres ou de la typographie changent un peu, mieux vaut donner un id au template et écraser le style dans la css avec #mon-template hx {etc ….}
  • Réinventer la roue en réécrivant ses propres viewlets, ou portlets de navigation. La plupart du temps il vaut mieux répartir les différentes parties décrites dans la charte dans les différentes viewlets existantes de Plone (personaltools, global actions …). 95 fois sur cent, ces viewlets sonts suffisantes. 95 fois sur cent, il faut même en enlever.

Pour rester simple il faudra commencer par alléger les feuilles de style de Plone et enlever tout ce que vous ne voulez pas. Et cette démarche va vous éviter un nombre incalculable d’ennuis ou d’incompatibilités avec les différents navigateurs.

II. Garder l’oeil ouvert

Le plus important quand on regarde une maquette graphique ce ne sont pas les pleins mais les déliés. Essayez de voir ce que les autres ne voient pas.

Le premier travail à faire est de définir les espacements, les margin et padding. Bien sûr ça va de pair avec les dimensions.  Alors par exemple la dimension des colonnes et le padding autour des portlets c’est primordial. Encore plus primordial est la largeur du portail et les marges qui vont autour. Si la largeur est fixe à 980px et que le contenu est centré horizontalement, ça prend deux lignes et votre feuille de style commence avec ça :

#visual-portal-wrapper {
width: 980px;
margin: 0 auto;
}

La deuxième chose concerne la typographie. Beaucoup de personnes se lancent dans l’intégration d’un site avec la mauvaise fonte et quand ils arrivent au bout sont obligés de tout recommencer à cause de ça.  Donc définir la police globale, et les polices de titre, les tailles de police (pas toujours facile).

La troisième chose concerne les couleurs :

  • ça a l’air bête mais quelle est la couleur du texte #333 c’est pas du noir et ça change tout
  • la couleur des liens
  • des liens survolés ou actifs
  • des liens visités
  • couleur des titres

Quelques trucs un peu moins importants comptent aussi :

Epaisseur et styles des bordures.

Si vous êtes un habitué vous aurez reconnu que nombre de ces choses importantes sont dans le base_properties.props associé à votre skin. Ce n’est pas pour rien que ce truc existe, et c’est par là qu’il faut commencer.

III. Templates de Plone

Actuellement il est très rare d’être obligé de surcharger le main_template ou d’autres templates de Plone parceque vous disposez des viewlets.

Ce qu’il faut faire :

  • surcharger les viewlets (avec un overrides.zcml) ce qui permet de réécrire les templates, les méthodes (n’oubliez pas les tests sur les nouvelles méthodes sinon votre chef de projet ne va pas être content) ou plus simplement associer une viewlet à un autre viewletManager (vous voulez des site_actions et personal tools dans le footer par exemple, c’est qq lignes dans le overrides et dans le profil)
  • réordonner les viewlets avec votre profil viewlets.xml
  • ajouter de nouvelles viewlets avec un configure.zcml

Ce qu’il ne faut pas faire sauf par exemple si vous êtes obligé d’ajouter des viewletManagers dans le main_template ce qui est rare, sachant qu’un viewletManager peutêtre ajouté dans un autre viewlet :

  • overloader les templates dans les skins (après ce sera très dur de faire un upgrade du site, pensez à ceux qui prendront la relève sur votre travail et au temps que ça va prendre de scruter les diff entre les templates sur la bonne version de Plone), un calvaire.
  • faire des templates dans les skins pour la même raison et parcequ’on ne peut pas tester ces templates sans lancer Zope. Utilisez plutôt les vues, c’est un peu plus long mais vous oeuvrez pour quelquechose de pérenne.

Bien sûr si vous manquez de temps ou de budget sur un projet rien n’interdit de faire les deux choses susdites. Cependant si vous voulez juste changer un « > » en « / » (breadcrumbs)  ou supprimer un élément graphique (remplacer le « search site » de la boîte de recherche par « OK ») personnellement je préfère faire un display: none en css ou changer le label via un minuscule jQuery, plutôt que d’overloader un template et compliquer la vie de ceux qui viendront après moi.

D’ailleurs si vous manquez vraiment de temps (par exemple vous devez faire le design d’un site en 1 jour) et que vous voulez déplacer les site actions et personal tools dans le footer, vous faites ça en trois lignes de jQuery et de css (après tout ce n’est que de la présentation):

C’est un exemple à ne pas suivre sauf si vous êtes pris à la gorge par un budget digne d’une aide aux pays en voie de développement :

/* d’abord on masque dans le css pour ne pas avoir l’effet que ça bouge en direct */

#portal-siteactions {
display: none;
}

#portal-personaltools-wrapper {
display: none;
}

Ensuite on bouge les personal tools dans les site actions puis les site actions dans le footer

javascript :

moveElements = function() {
var personalAc = jQuery(« #portal-personaltools li »);
var siteAct = jQuery(« #portal-siteactions »);
var footer = jQuery(« #portal-footer »);
siteAct.append(personalAc);
footer.html(«  »);
footer.prepend(siteAct);
}

jQuery(document).ready(moveElements);

ensuite on réafiche dans la css :

#portal-footer #portal-siteactions {
display: block;
}

et voilà ni templates (le pire) ni viewlets (le meilleur mais plus cher).

IV. Faut-il écraser les styles Plone par défault ?

La réponse est simple : si vous maitrisez bien la css et que vous manquez de temps vous pouvez choisir de ne pas écraser les styles Plone par défaut, même si ce sera au détriment des performances (taille de css envoyé plus importante), ce dernier point n’étant vraiment pas primordial si vous savez cacher correctement vos css. Le vrai problème étant qu’overloader des styles est beaucoup plus compliqué qu’il n’y parait, vous rencontrerez des tas de soucis avec IE et Safari par exemple.

Si écrire du css ce n’est pas votre tasse de thé, commencez par copier-coller base.css.dtml et public.css.dtml dans votre produit de skin et élaguez (ça va vous faire plaisir en plus), vous verrez qu’ensuite tout deviendra limpide et que si ça se trouve il ne sera même pas utile de surcharger IEFixes.css, et oui pour gagner du temps il faut savoir en perdre.

V. Eviter les hacks css au maximum

En général si vous avez besoin d’un hack pour Mozilla ou Safari c’est qu’il y a une erreur quelque part dans l’écriture de vos feuilles de style. Il ya bien sûr des cas particuliers (le vertical align dans un div par exemple nécessite des pirouettes inhabituelles).

Quant à IE, le IEFixes.css de plone est en général suffisant, pour ma part je le surcharge et j’enlève le *html devant tous les float bugs de manière à appliquer le patch également à IE7, ça résout pas mal de choses.

Pour éviter les bugs avec Safari éviter de surcharger les styles de Plone ou bien faites le proprement car si vous écrivez :

background: mycolor url(myimage) myreepat myposition;

et que plus bas vous surchargez pour le même style

background-image: url(mynewimage);

le background repeat est perdu.

Je ne sais pas vraiment pourquoi ….

V. Eviter les positions absolues

Bien sûr parfois on ne peut faire autrement et je comprends aussi ceux qui aiment la rapidité d’affichage, mais sauf si vous aimez absolument les ennuis je vous le déconseille pour skinner la globalité d’un site.
La position absolue est valable sur des petits tools en javascript, sinon essayez de faire sans, je sais que ce n’est pas toujours simple de manipuler des éléments flottants mais si tout le monde se casse la nénette à faire ça ce n’est pas pour rien.

Suite au prochain numéro :-)


Novembre 22, 2008
» Some Safari css fixes

You must know some things to adapt your css for Safari. Here’s some tips.

Background images

It’s a really strange bug.

You want a background image with no repeat or just an horizontal repeat.

As long as i can remember something, we were doing things like that :

#mystyle {
background: #mycolor url(myimage) myposition no-repeat;
}

If you want to be Safari compatible, just write :

#mystyle {
background-image: url(myimage);
background-position: myposition;
background-repeat: no-repeat; /* or repeat-x */
}

Otherwise background repeat and position do not work (you will get a beautiful but unwanted mosaic repeat with a 0 0 position).

Vertical align

In a div sometimes you need a centered vertical align, so you fix things like this for a 200px height cell with a table cell behavior :

#mydiv {
display: table-cell;
height: 200px;
vertical-align: middle;
}

Because you are really careful and meticulous or because you are in a hopeless case, you try to add :

overflow : hidden

Spoiled, I don’t know why but with Safari you must add :

max-height: 200px;

otherwise the height will be your css height + content height

Css hack for safari3 and webkit

Everybody know the « * html » hack for IE6, but if you want to put a webkit only declaration you must do :

html[xmlns*=""] body:last-child myStyleDeclaration {etc ….}


Novembre 2, 2008
» Plone et les grenouilles


Ca fait des mois que la communauté Plone s’est, en apparence pour les francophones, repliée sur elle -même, et qu’elle ne produit plus que des articles incompréhensibles pour le commun des grenouilles.

Normal car si de nos jours vous voulez un peu d’info sérieuse sur Plone (ou sur n’importe quelle autre techno du reste) sans maîtrtiser la langue anglaise c’est pas gagné.

De plus, en trois ans (depuis l’époque bénie de Zopera Zopeur et des petites guéguerres bien de chez nous … ) Plone a évolué, et comment ! … C’est une révolution mais nous y reviendrons.

Revenons dans notre petit village gaulois : si personne ne s’occupe de faire la communication nécessaire, les 3/4 des DSI français baissent la garde et vont s’orienter vers des technos Php épouvantables juste parcequ’elles s’apellent TINTIN ou PIF. Je trouvais ça drôle il y a quelques années, moi aussi j’aimais bien les écureuils, j’étais moi aussi très éclectique et abonné à Spirou, mais cette forme de retour sur le passé, je dis stop.

Plus sérieusement, c’est embêtant, la plupart des décideurs français qui ont un projet internet/intranet n’ont jamais entendu parler de Plone ou alors c’est un salarié sorti du grenier de leur grand-mère qui a osé le faire et bien-sûr le salarié en question a été gentiment remercié.

Plus embêtant, ceux qui s’intéressent au sujet et qui connaissent Plone ont fini par laisser tomber faute d’arguments francophones bien de chez nous.

Encore plus embêtant, les fans de Plone dont je fais partie, et qui connaissaient bien le sujet, ont sérieusement douté car le projet a connu une telle révolution qu’il était difficile pour tout le monde de s’y retrouver, bien des fois j’ai jugé la situation critique.

Aujourd’hui, personnellement j’ai changé d’avis, ah merde qu’est-ce-que j’ai pas dit, ici chez les grenouilles on dit retourner sa veste, on y reviendra …

      

Octobre 21, 2008
» 3 Colors Theme : a collective phantasy based theme

Since Plone base properties style could seems too rich for a standard use case, phantasy skin edit forms could be also too complex.

When i saw how easy it is to change some skin properties in a blog system like word press ( …),  i thought we need the same feature in Plone.

Collective Phantasy is done for that.

Building a new skin product with a standard static theme and a customized skin schema is something you can do easily with collective phantasy.

If you want an example, just test the « 3 colors theme » plone product.

In your buildout :

in instance eggs section add :

    collective.threecolorstheme

in zcml section add :

    collective.threecolorstheme
    collective.threecolorstheme-overrides

Relaunch your buildout.
Launch your zope instance.

In plone_control_panel you will get :

Check for « Three Colors Theme » Product, this will install the product and its dependencies :

Go back to the home page, of course the « static » theme has changed (my poor contribution to plone themes community)

We want to change the dynamic properties, so we click on « Contents » tab, and we can see that everybody is here : the dynamic root skin for portal, and the phantasy skins repository (read previous posts …) :

We want to build a new skin, so as we have seen in previous posts, in phantasy skins repository we add a new skin :

In this form you could see differences with a classic phantasy skin form (for developpers/integrators look at the code it’s just some easy Archetypes bidouille) :

- 3 colors only + mutators to change all colors

- an entire fieldset removed

- many fields unuseful in this theme are hidden

- some skin attributes added in schema

Go back to reality : just change some colors

Now we will import a skin sample provided in « three colors theme product ».

In alternate_skin folder you will find a zip file and a txt file (howtouseit.txt).

Click on « import images and files », choose the alternate_skin.zip file

Read howtouseit.txt and change some colors or properties

Use plone kss power to change images’ names quickly

CTRL-F5 to refresh the page, of course you need some design feeling to understand what’s happen here, but it’s not so complicated (…)

In the product you will find another example with another howtouseit.txt, here, then just add a folder and choose the good phantasy skin and you will get :

Loving Plone :-)


Octobre 13, 2008
» Using Collective phantasy with another plone theme product

When installing collective phantasy it will takes its skin properties from the current available plone theme.

You could see in screenshots below a customization of qPloneSkinWhiteBlack plone theme, using phantasy :


» Collective Phantasy

Today we will work on skinning Plone, you will see how easy it is, especially when using collective.phantasy.

This product is only plone3.1.x (and perhaps ++) compliant.

I suppose you know how to build a new plone instance using buildout. I know it’s not always so easy for Windows users, but keep cool, read documentations about buildout (it’s a really powerful feature), and send a comment here if you get problems with this question, i will try to help you .

So, in your plone3.1.x buildout.cfg, just add these two lines : In instance – eggs sections :

    collective.phantasy

In instance -zcml section :

    collective.phantasy

Now you could launch your buildout :

    bin/buildout -vvv

Then launch your Plone instance.

    bin/instance start

OK.

Install collective.phantasy in Plone

Go on your plone site > Add/Remove Products You will get this screen :

Check for « Collective Phantasy » product and Save the form.

This will install « Collective Phantasy » product and its dependency « Smart Color Widget » :

The portal look is changed, but it’s just an example, not the best wonderful design ever seen ;-) ,
so we will change it.

Change the portal skin

Go to your portal root, click on Contents :

You will get two new items :

- An Item called « Phantasy Skin repository », it’s a folder containing alternate skins for folders

- An item called « Plone’s logo, colors and border defaults », it’s the dynamic skin used for your portal, you can delete it and recreate it, but now we will just change it click on this item,
then click on « edit » tab

Click on « Colors » tab, change the background color value for « #f3f3fb » :

And save the form, here is the result :

Re-click on edit tabs, then on « dimensions » tab,

change the values for ‘portal width’ and « Portal horizontal position » like this :

And save the form :

hmm it’s better but we will do some new things.

First we will add our logo.

Go back to your skin, use the contextual menu : « Add new… », choose « Skin Image » :

Click on Browse (« Parcourir » in french ), choose your logo image on your HD :

Save the form. Go Back to your skin.

We will change the logo name in skin. Click on edit tab, then on « images » sub-tab.

Change the logo name value for « logo.gif » (the image id you’ve just uploaded), and save the form.

Here is the result :

Go back to your portal home page and refresh the page, CTRL-F5. If you want to see the left column as shown in next image you also need to change the portlet navigation property with « Manage portlets » …) :

Setting a new skin and choose this skin for a particular folder

See global tabs at top, Click on « Folder with other skin »

You see that the portal look is changed here. Ok. Go back to the Phantasy Skins Repository, click on Contents, you see here alternate skins which can be used by any folder :

Click on the only skin present here :

Oh, oh … the same look as we’ve seen somewhere before.

OK, now we will change everything, go back to the portal root > Contents tab, select the dynamic root skin and click on « copy ». :

Go back to the Phantasy Skins Repository, and click on « Paste » :

We will rename this skin, it could be practice, check the second skin and click on « rename » :

Then click on this skin to go on it. Now we will do always the same thing, click on « edit » and change background color, but take care because now the color value must cohabit with a future background image (use Firebug extension to help you) :

Create a css for your skin

Now we will do something special that’s not embed in Phantasy skin parameters. Edit a text file, save it on your HD as a a css file, here we call it « ornicat.css », we add a little new selector in this css, this selector add

a large left violet border to the page :

Create some images used by your skin

We create a global background image which can cohabit with the background color, using Photoshop or any picture dedicated software (we save it on local disk as « portal-background.gif ») :

We create a new logo with the same software (we save it as « logo-2.gif ») :

Post all these files in your skin

Create a zip archive with the 3 precedent files :

Go back to your browser, to your site and to your skin, click on « Import images and files » :

Click on « browse », choose your zip file on your local disk.

Click on import, wait during upload …

Upload is done

Setting up your special skin

Click on « Edit » tab, enter the css file id (ornicart.css here)

Click on « images » sub tab

- Change the logo name for the new logo id (logo-2.gif)

- add a body background image name with your background image id posted first (portal-background.jpg)

- change background image position for « Top right »

- change background image repeat for « Vertcal repeat »

- Save the form

Here is the result

Ah, i think it’s better

Give a folder a new skin

Go to « Folder with another skin », click on Edit, Below Phantasy skin, click on « Add », now you can browse the site for a new skin, Choose the « Alternate skin » we’ve made before.

Save the form Click on CTRL-F5 to refresh the page.

Now you can say « Skinning Plone is not so complex ». :-)


Juin 3, 2008
» plone buildout and windows vista

You are in the « sein des saints » of plone and buildout, and you know how to do a buildout on windows (congratulations), so i wont tell more about this. But if unfortunately, you need a buildout on Windows VISTA, you must patch your MingW installation (only for MingW 3.4.5) :

http://dessent.net/tmp/gcc-vista-3.4.5-20060117-1.tar.gz

Unzip and replace all files in your MingW 3.4.5 folder

Otherwise you will get many buildout errors, oeuf corse.