Wednesday, May 16, 2012

HOW TO SETUP WINE IN UBUNTU

HOW TO SETUP WINE IN UBUNTU

*** UPDATE 19-07-2006 (UK DATE SYSTEM ) This howto was originally written for breezy badger, I can now confirm it also works on dapper drake

*** UPDATE 15-12-2008 Updated for Intrepid Ibex, and fixed dead winetools link (thanks to Murdoc_of_puts post 485)

After a lot of searching here there and every where I finally know how to get wine working on my machine anyway, every time without fail, and as there is a lack of how to's on wine, I thought i would give the Ubuntu community something back. This is my first how to, so don't be to harsh if it dosen't work for you.

First we get the wine0.95.deb from winehq http://kent.dl.sourceforge.net/sourc...ehq-1_i386.deb

or if you want to open a terminal (alt+F2 then type gnome-terminal then enter) to download it use this command

Code:
wget http://kent.dl.sourceforge.net/sourceforge/wine/wine_0.9.5-winehq-1_i386.deb
In case your wondering why we are not downloading the latest version of wine its because internet explorer install breaks on newer versions and you will probably need internet explorer to get other programs working, but we will update wine after, so don't worry

Right so we got our Wine .deb so lets unpackage it in our terminal dont forget to change directory to where you downloaded wine (if you used the above command you should already be there)

Code:
sudo dpkg -i wine*.deb
ok, so we no have wine, but how do i use it, set up a C:/ D:/ etc i hear you cry, let alone install anything, well here come the great little app called winetools

I have now learned that winetools has at least one dependancy, pointed out by replies on this forum, here is the command for installing it (added 1st April 06, after 12 not a april fool btw)

Code:
sudo apt-get install libgtk1.2
wine tools can be downloaded here

or if your still with me in the good old terminal you can use this command

Code:
wget http://www.sfr-fresh.com/linux/misc/winetools-0.9jo-III.tar.gz
ok, so we got this great tool no we need to unpack it

Code:
tar -xf winetools*
and install it

Code:
cd winetools*
sudo ./install
Done so lets start this wonderfull tool with this

Code:
wt
you will get loads of messages popup about not being configured etc, just keep clicking ok oh and that you should also own a copy of windows to use some of these tools. Yeah Yeah on with the plot.

You should finally get to a menu

So first we go for base setup, then create a fake windows drive
Next winetools will find your cdrom for you so it can set it up for wine
Followed by a username and organization, I Just leave theese as is
After a few fake windows restarts later we are told fake drive completed. Yippee

We are back to the base setup menu, now select DCOM98 and then go down the list installing all the programs on the list, obvioulsy only do internet explorer in your language, the reason we have left the Arial font out is because the link to this is dead, but we will sort this later. Just click next and ok on everything, im sure you know how window installers work.

Ok so we have finished the first list, hit the main menu button to get us back to the start.

next click install windows system software then click ok

again install everything thats in the list from top to bottom in your own language, and install visual basic 5 & 6

ok, so now we gotta sort out theese fonts as the links that winetools uses to retrieve them is dead, so click main menu followed by exit to leave winetools

now then back to our friend the terminal
ok so first we need to make and move to the directory where winetools would have downloaded the fonts

Code:
mkdir ~/winetools/fonts
cd ~/winetools/fonts
you might get an error saying the file exsits, if you do don't worry just continue

Next we download the fonts from a link that is still around at the time of writing this, you might want to copy and paste this one into your terminal

Code:
wget http://kent.dl.sourceforge.net/sourceforge/corefonts/andale32.exe && wget http://kent.dl.sourceforge.net/sourceforge/corefonts/arial32.exe && wget http://kent.dl.sourceforge.net/sourceforge/corefonts/arialb32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/comic32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/courie32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/georgi32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/impact32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/times32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/trebuc32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/verdan32.exe &&  wget http://kent.dl.sourceforge.net/sourceforge/corefonts/webdin32.exe
Ok, so we now have the fonts downloaded, next back to winetools to install them

Code:
wt
Select base setup again then install true type font arial

Next main menu then select Install Microsoft true type corefonts, yet again go all the way down the list until you have installed all the fonts.

done that, so main menu and exit winetools

Ok so we should now have a working wine, with internet explorer installed and windows media player 6 hopefully :s

we should be able to start Internet Explorer with the following

Code:
wine "/home/USERNAME/.wine/c/Program Files/Internet Explorer/IEXPLORE.EXE"
Dont forget to change USERNAME to your own username

With any luck your using internet explorer now

although we dont want to have to write this in everytime we want to start internet explorer, so right click the desktop and create a launcher and paste the previous code in there for a desktop shortcut, or make a menu shortcut which ever you prefer.

Here is the code for Outlook and Windows Media Player

Code:
wine "/home/USERNAME/.wine/c/Program Files/Outlook Express/msimn.exe"
and

Code:
wine "/home/USERNAME/.wine/c/Program Files/Windows Media Player/mplayer2.exe"
and really thats about it, you can also navigate using your file browser and double click .exe files and wine will launch them, like installers for programs and so on, then its just a case of finding the .exe that starts the program and making your custom launcher for it, your wine c: should always be found in /home/USERNAME/.wine/c. As long as know a bit about the windows file layout you should have no problem in finding them, always remember when creating your launchers that linux is case sensitive, so dont forget the caps.

Two last things to do

Firstly updating wine 0.95 to the latest version, remember we had to use 0.95 because internet explorer will not install on newer versions, although this maybe fixed now. There is no need to panic though, we just add a wine repository to our sources.list like this.

Code:
sudo gedit /etc/apt/sources.list
then add this line to the bottom of the file

http://www.openoffice.de/wt/winetools-0.9jo-III.tar.gz

then save your sources.list and run the following in terminal to update your wine installation

Code:
sudo apt-get update
sudo apt-get upgrade
This should update wine to the latest version released by wineHQ, and will always be updated with the rest of your updates when a new version is released, Good hey

The second thing to do is to tell you about the winecfg command

Code:
winecfg
This little panel allows you to change the default wine settings, like which windows version to try to act as, and what builtin and native dll's to use, I would suggest leaving the global settings to windows98 as this seems to work best, but you can change the windows version for individual .exe's if a program only works on a certain version of windows, if a program dosen't quite work right this is the place to go, although the full usage of winecfg is a bit beyond the scope of this howto, you should get familiar with it quite soon

If you have problems with a certain program i find it always pays to just put in a google search "program name winehq" and you will usually find the program in the winehq database and find out what success people have had at getting the program to work and what they did to achieve it, very helpfull

One last point, if you use any programs that reside in the windows system tray then the system tray icons do not show up, a workaround is to open up a kde application that uses a tray icon and then the windows tray icons will appear, i.e i have amarok start when gnome starts, kalarm is a good one to use if you dont use amarok, even after you quit your kde program the windows icons will remain. I believe this shouldn't be a problem for KDE users.

Anyway hope this was some help to a least one person out there, and I will probably add a MSN Messenger HOWTO this as soon as i get the time, let me know how you get on, In the meantime happy wineing

Friday, April 20, 2012

16 Very Useful Smarty Scripting Tips and Techniques to Make Templates Smarter

16 Very Useful Smarty Scripting Tips and Techniques to Make Templates Smarter

  1. HTML Code Reuse

    Use {capture} tags to assign any output it generates into a variable that you can use to display the captured content multiple times throughout your templates.
    Assign the output to the variable "nav":
    {capture name='nav'}
    <ul>
    {section name=item loop=$nav}
      <li><a href="{$nav[item].url}" title="{$nav[item].title}">{$nav[item].label}</a></li>
    {/section}
    </ul>
    {/capture}
    Show the captured content.
    {$smarty.capture.nav}
    You can also assign the output to a template variable.
    {capture name='nav' assign='navmenu'}
    Then display the content using the variable.
    {$navmenu}
    When name is not specified, "default" is used and can be displayed like this:
    {$smarty.capture.default}
  2. Passing Variables from Sub-Templates

    While using $GLOBALS array via {php} would do the trick, using {capture} is neat and recommended considering most template designers don't want to get their hands dirty on PHP. After all, smarty template files are not meant for PHP codes.
    In header.tpl:
    {capture name='columns'}3{/capture}
    Then, in index.tpl:
    {include file='header.tpl'}
    {if $smarty.capture.columns == '3'}
    . . .
    {/if}
    {include file='footer.tpl'}
    Can even access the variable inside footer.tpl:
    {if $smarty.capture.columns == '3'}
    . . .
    {/if}
  3. Including Sub-Templates using Custom Delimiters

    To include a sub-template that inserts values of template variables in embedded JavaScript or CSS rules, use {php} tags, instantiate a new Smarty object, assign values to template variables, and finally, display the sub-template.
    main.tpl
    {php}
    $smarty = new Smarty;
    $smarty->left_delimiter = '<!--{';
    $smarty->right_delimiter = '}-->';
    $smarty->assign('size', '36px');
    $smarty->assign('pre', 'Great');
    $smarty->assign('post', 'Templates');
    $smarty->display(message.tpl');
    {/php}
    message.tpl
    <style type="text/css">
    <!--
    h2 {font-size: <!--{$size}-->}
    -->
    </style>
    <h2>Welcome to the World of <!--{$pre|capitalize}--> Smarty  <!--{$post|capitalize}--></h2>
    <script language="javascript" type="text/javascript" >
    <!--
    function welcome(){
      alert('Welcome to the World of <!--{$pre|capitalize}--> Smarty  <!--{$post|capitalize}-->');
    }
    welcome();
    -->
    </script>
    Above code will display "Welcome to the World of Great Smarty Templates" with font size 36px and pops up an alert with same message.
  4. Debugging Smarty Templates

    Smarty has a debugging console that allows you to easily examine assigned template variables, included templates and config file variables for the current template.
    To enable the debugging console:
    1. Set Smarty $debugging property to true.
      <?php
      $smarty = new Smarty;
      $smarty->debugging = true;
      ...
      ?>
    2. If the debug console window does not pop up when you load the page, set $debug_tpl property to the path of your debug template. By default, Smarty will look for the "debug.tpl" in SMARTY_DIR. This file is included in Smarty distributions and can be found in library "libs/" folder.
    The easiest and quickest way to enable debugging console is by placing a {debug} tag in your templates. It works regardless of the $debugging settings in the php script. However, it only allows you to see all the available variables within the scope of the current template.
    Example usage:
    <h1>{$title}</h1>
    {debug}
    <p>{$description}</p>
  5. Accessing Request Variables from Smarty Templates

    Request variables available in PHP scripts can be accessed from your Smarty templates through the reserved template variable {$smarty}. Request variables include $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, and $_SESSION.
    Examples:
    Output the value of $_GET['page'] from the url "http://www.jampmark.com/index.php?page=about"
    {$smarty.get.page}
    Output the value of $_POST['page'] from a posted form
    {$smarty.post.page}
    Output a cookie variable, $_COOKIE['status'] from request header
    {$smarty.cookies.status}
    Output a server variable, $_SERVER['SERVER_NAME']
    {$smarty.server.SERVER_NAME}
    Output a system environment variable, $_ENV['PATH']
    {$smarty.env.PATH}
    Output a session variable, $_SESSION['id']
    {$smarty.session.id}
    Output the value of "username" from merged get/post/cookies/server/env
    {$smarty.request.username}
  6. Accessing Template Variables from PHP script

    You can access template variables using Smarty method get_template_vars() in PHP scripts. However, template variables are only available after or during template execution. The latter can be achieved by embedding PHP code directly into the smarty template using {php} tags or by including a php file using the built-in function {include_php} tag.
    Consider the template code:
    {assign var='title' value='Smarty Templates'}
    Accessing variables after template execution:
    // execute the template and return the result to a variable
    $page = $smarty->fetch('index.tpl');
     
    // will output "Smarty Templates"
    echo $smarty->get_template_vars('title');
     
    // assign value to the variable
    $smarty->assign('title', 'The Great Smarty Templates');
     
    // this will output "The Great Smarty Templates"
    echo $smarty->get_template_vars('title');
     
    // this will dump all variables assigned in the template
    var_dump($smarty->get_template_vars());
    There are two (2) ways to access variables during template execution from inside {php} tags.
    {php}
    // using $this->_tpl_vars
    echo $this->_tpl_vars['title'];
     
    // using $this->get_template_vars() method
    // the variable $this, is a smarty object
    echo $this->get_template_vars('title');
    {/php}
  7. Variable Substitution in String with Double Quotes

    This works similar to that of PHP where variables embedded in a double quoted string are expanded to their values.
    • Simple substitution:

      With $filename having a value of "footer", the file attribute below will have a value of "templates/footer.tpl".
      {include file="templates/$filename.tpl"}
      Code below won't work because string is surrounded by single quotes.
      {include file='templates/$filename.tpl'}
    • Array indexes

      Assuming $module[1] contains "user_menu":
      The $module[1] below will be replaced with “user_menu” and will translate into "user_menu.tpl".
      {include file="$module[1].tpl"}
      With $index value equal to 1, code below will do the same thing as above. In this case, enclose with backticks.
      {include file="`$module[$index]`.tpl"}
    • Associative Arrays

      Let's put $item['name'] equals ""Computer":
      The variable $item.name below will be replaced with "Computer" so value will be "Computer unit".
      {assign var=’label’ value="`$item.name` unit"}
      With $prop value equals to "name", the following is equivalent to the above.
      {assign var='label' value="`$item.$prop` unit"}
    • Objects

      Say, we have an object variable where $book->title contains "Smarty Templates".
      The $book->title below will be replaced with "Smarty Templates" so $msg will have value of "My Smarty Templates book".
      {assign var='msg' value="My `$book->title` book"}
      With $property equal to "title", $msg will have same value as above.
      {assign var='name' value="`$book->$property`"}
      Note: Always enclose variable names with backticks (`) when they contain dots (.), object references (->), or when using index variables for arrays.
  8. Handling Blank Template Variables

    Blank template variables may break your HTML table layout. It may also cause <img> tags to load your web page in the background and generate multiple entries in the access log for every single visit due to src attribute being empty.
    Use {if} tag to output a default value when a variable is empty. Or use the shortcut, the "default" variable modifier.
    Consider the following code that outputs &nbsp; inside HTML table cell:
    <table><tr><td>
    {if $user eq ''}
      &nbsp;
    {else}
      {$user}
    {/if}
    </td></tr></table>
    The shortcut:
    <table><tr><td>{$user|default:'&nbsp;'}</td></tr></table>
    Here is a code that handles <img> src properly:
    <img src="{if $image_url eq ''}/images/default.png{else}{$image_url}{/if}" />
    Or simply:
    <img src="{$image_url|default:'/images/default.png'}" />
    The shortcut makes a cleaner code but using it throughout your templates can be a bit ugly.
    Consider the code below:
    <a href="{$image_url|default:'/images/default.png'}">
    <img src="{$image_url|default:'/images/default.png'}" />
    </a>
    <p>Path: {$image_url|default:'/images/default.png'}</p>
    Here is a much cleaner version using {assign} tag with  default .
    {assign var='image_url' value=$image_url|default:'/images/default.png'}
    <a href="{$image_url}">
    <img src="{$image_url}" />
    </a>
    <p>Path: {$image_url}</p>
  9. Passing Variables to Sub-Templates

    It is common for web developers and web designers to place repetitive contents into separate template files and {include} them where needed. One typical example is header.tpl which includes the html title tag. Suppose need it to show different page titles depending on which page included it. You can do that by placing "title" as attribute of {include} tag and this is how we pass parameters to sub-templates in Smarty
    Example template code that includes header.tpl with parameter "title".
    {include file='header.tpl' title='Welcome!'}
    {include file='footer.tpl'}
    In header.tpl
    <html>
    <head>
    <title>{$title|default:'Smarty World'}</title>
    </head>
    <body>
    In footer.tpl
    </body>
    </html>
  10. Formatting Numeric Outputs

    You don't need to assign multiple variables with same values in different formats because there is a variable modifier in Smarty that allows you to format output. "string_format" uses same formatting syntax in sprintf() function in PHP.
    Example:
    {$number}
    {$number|string_format:’%.2f’}
    {$number|string_format:’%d’}
    With $number equal to 23.5787446, the code above will output:
    23.5787446
    23.58
    24
  11. Handling Dates

    As a rule of thumb, PHP coders should always pass dates to Smarty templates as timestamps. This allows template designers to use the "date_format" modifier for full control over date formatting. You also make it easy to compare dates if necessary.
    Default date format:
    {$createDate|date_format}
    Will output:
    Feb 28, 2009
    Custom date format:
    {$createDate|date_format:'%Y/%m/%d'}
    Will output:
    2009/02/28
    Comparing dates:
    {if $startDate < $endDate}
      . . . do something . .
    {/if}
    To convert {html_select_date} output into timestamp format in PHP, use the function below:
    <?php
    function makeTimeStamp($year='', $month='', $day='')
    {
       if(empty($year)) {
           $year = strftime('%Y');
       }
       if(empty($month)) {
           $month = strftime('%m');
       }
       if(empty($day)) {
           $day = strftime('%d');
       }
     
       return mktime(0, 0, 0, $month, $day, $year);
    }
    ?>
  12. Obfuscating E-mail Addresses

    When showing e-mail addresses on your web pages, make sure they are obfuscated to somehow hide them from spam bots. In Smarty, you can use {mailto} tag to obfuscate an e-mail address. It works by scrambling the e-mail address using Javascript and embeds it in the HTML source. The e-mail address will still be readable by humans while giving spamming bots hard time to read.
    Example:
    <div id="contact">Contact us at 
    {mailto address=$emailAddress encode='javascript' subject='Hi Smarty'}
    </div>
  13. Alternating CSS Styles

    Displaying rows of information in alternating background colors is a great way to improve readability. In Smarty, you can use the {cycle} tag to set alternating CSS styles.
    Here is a sample code that sets "odd" or "even" css class to tags in alternates.
    <table>
    {section name=item loop=$items}
      <tr class="{cycle values='odd,even'}">
        <td>{$items[item].title}</td>
        <td>{$items[item].description}</td>
      </tr>
    {/section}
    </table>
    Then set CSS "background-color" property with different colors for each CSS class.
  14. Fetch and Display Contents on Demand

    Traditionally, inserting new components into your templates would require adding data collection logic to the PHP script. On the reverse, removing components from your templates would also require removal of data collection logic from PHP script to optimize its performance.
    This can be a maintenance nightmare for large and complex projects especially when PHP programmer and template designer are two different people.
    The solution is to write component functions that are executed on demand when triggered by the template.
    There are 2 ways to write on demand scripts:
    1. Use the {insert} tag

      It works by calling a user-defined php function that begins with "insert_" and inserts the return value on the template where the {insert} tag was placed. The tag is useful for displaying dynamic contents because its output is never cached regardless of the template cache settings.
      The PHP code:
      <?php
      require 'Smarty.class.php';
      $smarty = new Smarty;
      $smarty->display('index.tpl');
       
      function insert_getNews($params)
      {
        if ($params['type'] == 'latest') {
          // retrieve news items and process
        }
        // return the result
        return $html;
      }
      ?>
      The template code in "index.tpl":
      <div class="news">
      <h3>Latest Smarty News</h3>
      {insert name='getNews' type='latest'}
      </div>
    2. Write your components as plugins

      Plugin is a module in its own file that contains PHP script for fetching necessary data and assigns them to template variables. It is always loaded on demand that you don't have to worry about adding and removing lines of logic from your PHP scripts.
      As an example, here is a simple Smarty news plugin.
      function.news.php – observe naming convention and put in plugins directory usually "smarty/libs/plugins" otherwise set the $plugins_dir.
      <?php
      // function for fetching news items
      function fetch_news($symbol)
      {
        // the news items could be queried from a database
        // but for this example we just create and return an array of items.
        $items = array(
        array('title'=>'Smarty News', 'description'=>'Great Smarty Templates'),
        array('title'=>'PHP News', 'description'=>'Smarty Templating Engine'),
        );
        return $items;
      }
       
      function smarty_function_news($params, &$smarty)
      {
        // call our custom function
        $news = fetch_news($params['symbol']);
       
        // assign template variable
        $smarty->assign($params['assign'], $news);
      }
      To use Smarty news in your index.tpl for display,
      {news symbol='SMARTY' assign='items'}
      <ul>
      {section name=item loop=$items}
        <li><h3>{$items[item].title}</h3><p>{$items[item].description}</p></li>
      {/section}
      </ul>
  15. Using CSS and Javascript Codes in a Smarty Template

    By default, Smarty parses anything that is inside { and } characters including those used in CSS rules and Javascript functions. Without proper coding and escaping techniques, your page will render into a disaster.
    There are four (4) ways to escape from Smarty parsing:
    1. Separate your CSS and Javascript codes into their own files and include them into your template using standard HTML methods.
      Linking a CSS file:
      <LINK REL=STYLESHEET HREF="style.css" TYPE="text/css">
      Including a Javascript file:
      <script type="text/javascript" src="popup.js"></script>
    2. Enclose embedded CSS and Javascript code with {literal} and {/literal} tags so Smarty engine would leave them alone.
      Embedding CSS:
      <style type="text/css">
      <!--
      {literal}
      p {text-indent: 10pt}
      body {margin:0; padding:0;}
      {/literal}
      -->
      </style>
      Declaring embedded Javascript function:
      <script language="javascript" type="text/javascript" >
      <!--
      {literal}
      function hello_world(){
        alert('Hello Smarty World');
      }
      {/literal}
      -->
      </script>
    3. Change Smarty's $left_delimiter and $right_delimiter to custom delimiter strings so you can use curly braces in your templates. In addition, it would allow you to insert template variable values into your CSS and Javascript codes to make them dynamic on the fly at server side.
      The PHP code:
      <?php
      require 'Smarty.class.php';
       
      $smarty = new Smarty;
       
      $smarty->left_delimiter = '<!--{';
      $smarty->right_delimiter = '}-->';
       
      $smarty->assign('title', 'The Smarty Template Engine');
      $smarty->assign('element', 'h1');
      $smarty->assign('size', '36px');
      $smarty->assign('popup', 'alert');
      $smarty->display('index.tpl');
      ?>
      The Smarty Template "index.tpl":
      <head>
      <style type=”text/css”>
      <!--
      <!--{$element}--> {font-size: <!--{$size}-->}
      -->
      </head>
      <body>
      <<!--{$element}-->><!--{$title}--></<!--{$element}-->>
      <script language="javascript" type="text/javascript" >
      <!--
      function show_popup()
      {
        <!--{$popup}-->('<!--{$title}-->');
      }
      //-->
      </script>
      </body>
      The code above will output:
      <head>
      <style type="text/css">
      <!--
      h1 {font-size: 36px}
      -->
      </head>
      <body>
      <h1>The Smarty Template Engine</h1>
      <script language="javascript" type="text/javascript" >
      <!--
      function show_popup()
      {
        alert('The Smarty Template Engine');
      }
      //-->
      </script>
      </body>
    4. Use {ldelim} and {rdelim} tags in place of { and } in defining your CSS rules and JavaScript functions assuming the default delimiters are set. This is not practical for real-world use and it will break when delimiters are set to other strings.
      Define CSS rules:
      <style type="text/css">
      <!--
      p {ldelim}text-indent: 10pt;{rdelim}
      body {ldelim}margin:0; padding:0;{rdelim}
      -->
      </style>
      Will output:
      <style type="text/css">
      <!--
      p {text-indent: 10pt;}
      body {margin:0; padding:0;}
      -->
      </style>
  16. Caching Smarty Templates

    Caching speeds up calls to display() and fetch() methods by saving its output to a file. This file is then displayed instead of regenerating the output. Use caching if your content does not change very often. Set $caching = 2 and use $cache_lifetime to control how much time you want to keep the cache enough to display fresh changes on your contents.
    Set caching on:
    <?php
    require 'Smarty.class.php';
    $smarty = new Smarty;
     
    // When $caching = 1,
    //   $cache_lifetime = 1 will force the cache to never expire
    //   $cache_lifetime = 0 will cause the cache to always regenerate
    // When $caching = 2,
    //   $cache_lifetime sets the cache expiry which can also be set for individual template.
    $smarty->caching = 2; // lifetime is per cache
     
    // Regenerates cached content if any templates or config files that are part of this cache are changed 
    $smarty->compile_check = true;
     
    // $smarty->force_compile = true; will force the cache to always regenerate
     
    // set the cache_lifetime for index.tpl to 5 minutes
    $smarty->cache_lifetime = 300;
    $smarty->display('index.tpl');
     
    // set the cache_lifetime for home.tpl to 1 hour
    $smarty->cache_lifetime = 3600;
    $smarty->display('home.tpl');
    ?>
    2 things to consider seriously when implementing caching:
    1. It is not recommended to put the cache directory under the web server document root. Set $cache_dir to a directory not accessible from the web.
    2. Make sure the cache directory is writeable by the web server.
There you have it. The 16 Smarty scripting tips and techniques to help you build smarter templates for your Smarty web projects.
For anything else, visit the official web site of Smarty Template Engine for PHP
Got Smarty tips not included here? Feel free to post them below.

Tuesday, April 17, 2012

cross-browser-html5-forms-using-modernizr-webforms2-and-html5widgets


Creating Cross Browser HTML5 Forms Now, Using modernizr, webforms2 and html5Widgets

July 27th, 2010 by zoltan · 23 Comments

Updates:

Range:
Placeholder:
Color:
Working example HTML5 Form using Modernizr, webforms2 and my new script, html5Widgets. Go ahead … try them out. You know you wanna!
Calendars, colour swatches, sliding widgets, client side validation: this is the nirvana that the HTML5 forms module promises. Some would say “So what? I’ve seen this on the web for years!”, and they’d be right. There have been some really brilliant people coding some really interesting widget and validation frameworks, so why should we change?
  • Ease the markup learning curve: HTML5 form widgets and validation have been built to be as dead simple to markup as a select box with no JavaScript knowledge required
  • It’s a W3C standard: so you know that it’ll work for years to come and if you have problems, you could always ask almost anyone in the web development community for help.
  • Cellular phone support: HTML5 form fields will have optimized user interfaces appropriate for the type of device. Blackberry already has optimized versions of the date/time and color widgets and, according to Mark Pilgrim’s article A Form of Madness, the virtual keyboards that appear when using HTML5 form fields are optimized for the data being input.
  • Web development tools will have to support it: It’s a safe bet that Aptana, Dreamweaver, and all the other IDEs out there will have HTML5 support.
  • It’s HTML5: when you tell your non-techie co-workers that you use it, you will be the envy of all — after all, it must be five times better than regular HTML, right? Your boss will be so impressed that you are now a guru in this futuristic technology with a cool numbered acronym that he or she will give you a big fat raise!!! (Okay, okay. Don’t try to laugh too hard … your co-workers will start to worry).

The Support Dilemma

Unfortunately, today’s support for the HTML5 Form Module is spotty with each browser supporting different parts of the specification. Take a look at Wikipedia’s HTML5 Forms comparison chart. You’ll see each browser supporting a different set of features, but the lowest common denominator they all support is rather small.

But I Want To Use It Now!!!

HTML5 Forms started off as WebForms 2.0 back in 2004, so I wasn’t surprised to see that a few developers had already coded some JavaScript implementations. Weston Ruter’s cross browser library, webforms2.js, implements a huge chunk of it, including parts that didn’t make the transition from WebForms 2.0 to HTML5 forms (e.g. Webform 2.0′s Repetition Model).
Since widgets weren’t implemented in webforms2, I created html5Widgets.js. This interface library is independent of webforms2 – if all you want is a cross-browser HTML5 form with validation, then all you need is the original webforms2.js. If you want special widgets that are not available for all browsers, include html5Widgets.js. Since I did not want to re-invent the wheel by creating widgets from scratch, html5Widgets.js uses some really nice third party JavaScript libraries to create them (more on that below). It also uses Modernizr to detect if there is native support for each of the HTML5 form widgets – if not, html5Widgets steps in to put the right widget in place. To save bandwidth, developers only need to include the third party libraries for the widgets they need.
In the rest of this article, I will go over different parts of the HTML5 specification and show how you can use them in your applications today, step-by-step. Each section will state which browser natively supports that part of the specification, and what is needed for browsers that don’t. Eventually, when the browser manufacturers catch up with the standard, you won’t need to use any JavaScript at all.

Form Validation Using the required and pattern Attributes

The required attribute makes an input field mandatory and forces the user to enter in a value in order to submit the form data. The markup is simple

(Note:, you can also just use required on its own if you aren’t trying to be XHTML compliant.)
The pattern attribute forces the user to enter in a value using a specified format. It uses regular expressions to define this format. For example, if you want to force the user to input a U.S. Zip Code inside a form field, you would use the following markup.
<--
     zip code regular expression from
     http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256F6B005294C2
-->

Note that required and pattern are independent from each other. You can have a pattern set on a form field without it being mandatory (i.e. the pattern would only be checked if the user enters in data into the field).
Opera 10+ (mobile and desktop editions) is the only browser that supports the validation routines natively. To use this in all other browsers, all you need is to include the following script tags in the head of your document.

Let’s take a look at how this looks visually:
Opera 10+ Windows Firefox 3.6 with webforms2.js
[Screenshot of HTML5 Validation using Opera] [Screenshot of HTML5 Validation using Firefox and webforms2.js]
Note the “starred” style of the form field — this is not the default look and feel of the required fields, but something I added with a simple amount of CSS:
input[required], select[required] {
 background: #ffffee url("../images/asterix.gif")  no-repeat left 2px;
 padding-left: 1.5em;
 width: 13.5em !important;
}
(This CSS does not work in Internet Explorer 6. Given that everything else in this article does, I hope the reader will overlook this one oversight considering that this browser should have entered retirement years ago (and have its driving license taken away, and shipped off to some really horrible nursing home watching really crappy talk shows all day and eating bad food …)
See an example of pattern and required in action.
Note that the same validation framework checks the values of inputs of type email, url and number to ensure that the values are in their respective valid formats. As an added bonus, if you are using the iPhone or iPad version of Safari, the virtual keyboard that appears will be optimized for these type of form fields (e.g. when editing a number field, the keyboard that appears contains only digits and the “+”, “-”, and “.” keys. This is native behaviour for iOS, and I hope other mobile browsers, such the Android’s, follow suit.

The autofocus Attribute

The autofocus attribute allows developers to choose which element has focus when the page is loaded. The Google front page has done this via JavaScript, and now, 12 years later, there is finally an HTML attribute to easily handle this.

Safari, Chrome and Opera support it natively. To make it work in other browsers, include the webforms2.js library, as we did in the required and pattern examples.
See an example of autofocus in action

The placeholder Attribute

A placeholder is a great visual cue to communicate any special information about a field (e.g. a description
of the data to be input, if the field is required, etc).

An example of placeholder text.  The text disappears when the field has focus or if the user types information into the field.
An example of placeholder text. The text disappears when the field has focus or if the user types information into the field.

Syntax is simple:

Safari, Chrome and Firefox support this attribute natively. To make it work in other browsers, it is necessary to load the html5Widgets library, with the necessary supporting libraries:





What do these libraries do?
  • modernizr is used to detect which HTML5 attributes and tags are supported by the users’ browser
  • html5Widgets is what actually does the placeholder logic, with EventHelpers.js providing cross-browser event-handling routines.
See an example of the HTML5 placeholder
tag in action.

The range Input Type and output Tag

Easily my favourite of the HTML5 widgets, range gives developers a sliding control to put inside their forms.
The syntax is simple:

The min and max attributes contain the minimum and maximum values, and step denotes by what increments the range slider increments by when moved. Note that you can use these attributes with the number input type as well, but instead of having the fancy interface, it will use the validation engine to ensure the value follows what these attributes dictate.
At the time of this writing, Opera and WebKit based browsers (like Safari and Chrome), support it natively, and html5Widgets uses the Frequency Decoder Slider Widget to implement it in unsupported browsers. To ensure cross-browser HTML5 range element goodness, place the following script tags in your document:















Take a look at the screenshots below. You will see that the way a range field varies among the browsers that natively support it, and even in some of the browsers that use html5Widgets:
Explorer 6.x+
(html5Widgets support)
Firefox 3.5+
(html5Widgets support)
Safari 4.0+
(native support)
Chrome 3.0+
(native support)
Opera 10.0+
(native support)
Windows Screenshot of range field for Internet Explorer 6 Screenshot of range field for Windows Firefox Screenshot of range field for Windows Safari Screenshot of range field for Chrome Windows Screenshot of range field for Windows Opera
Mac Not Applicable Screenshot of range field for Mac Firefox Screenshot of range field for Mac Safari Screenshot of range field for Chrome Mac Screenshot of range field for Mac Opera
Linux Not Applicable Screenshot of range field for Linux Firefox Not Applicable Screenshot of range field for Linux Chrome Screenshot of range field for Linux Opera
The output tag can be used to show the value of a field, or the result of an operation performed on a number of fields, using JavaScript expressions. Although the output tag may calculate fomulas referencing any form fields, it is useful especially for the range input type so users can see what value the range element is pointing to:
-

The contents of the output tag is the default value. Note the this.value syntax – I am not sure why the W3C HTML5 working group decided it was needed (why not just have the formula?), but it is. If there are other types of expressions supported in the final specification, they are not supported by html5Widgets at this time. Note that in order to apply CSS to the output tag in IE, it is necessary to use Remy Sharp’s HTML5 Enabling Script.
See an example of the range input being used with the output tag.
See an example of the output tag being used without a range field.

Update (May 12. 2011):

Since this article was written, the onforminput event has been deprecated in favor of the oninput. I have updated html5Widgets to support oninput, and have written article about its oninput support. I encourage you to see the different between the above to examples and the oninput method of using the output tag with range and without range

The datetime, datetime-local, date, week and week Input Types

At the time of this writing, Opera is the only desktop browser that supports HTML5 date fields. To support the other browsers, html5Widgets uses a slightly modified version of DynArch.com‘s Ex-”Coolest” DHTML Calendar (I decided not to use the coolest one because the Ex-Coolest has a more permissive license and it works really well). Now all browsers can support the datetime, datetime-local, date, month and week input fields, and submit these values in a consistent format.
Here are the scripts needed for the browsers that need it:













Note that the calendar widget uses language packs and that I am using the English one (calendar-en.js. Other language packs are included.
Below is a comparison between Opera’s native date widget vs. the one provided by the DynArch/HTML5Widget combo:
DateTime Widget Month Widget
Opera Windows
Opera Mac
Firefox 3.5+ Windows
(html5Widgets support)
It looks like the native calendar for Opera for Mac is a smaller than the Windows version – hopefully this is just on my copy of the browser.
The display formats, and they values that they submit to the server, are pretty much the same
Input type Format displayed on page Format sent to server
datetime yyyy-mm-dd HH:MM yyyy-mm-ddTHH:MMZ
datetime-local yyyy-mm-dd HH:MM yyyy-mm-ddTHH:MM
date yyyy-mm-dd yyyy-mm-dd
month yyyy-mm yyyy-mm
week yyyy-mmW yyyy-mmW
See the HTML5 date widgets in action.
Note: In this example, The Opera Mobile Windows Emulator incorrectly displays the datetime and datetime-local calendars in the upper left-hand corner of the screen, but not the other ones. Since this is Opera’s own calendar widget, and not html5Widgets’, this bug will have to fixed by Opera.

Screenshot of Opera Mobile bug
Screenshot of Opera Mobile bug

The color Input Type

Currently none of the desktop browser manufacturers support the color input type (although the new WebKit based Blackberry browser seems to have a neat implementation). While we wait to see how the major browser manufacturers decide to implement color, you can use html5Widgets’ implementation which uses Jan Odvarko‘s jscolor. The script has been configured to allow only allow lower case hexadecimal rgb values to be entered, and that a blank value not be allowed, as per the W3C spec.
Here are the script tags needed to implement this in all browsers:








Below is a comparison between the Blackberry’s implementation (grabbed from the Blackberry Development Blog) and HTML5Widget/jscolor’s.
Blackberry Web Browser Firefox 3.5 with html5Widgets.js
HTML5 Color form field, Blackberry HTML5 color input field with html5Widgets and jscolor.
See HTML5Widget’s implementation of the
color input type.

Note: Like other HTML syntax, color uses the unfortunate American spelling instead of the Queen’s Proper English (i.e. colour). Ensure you spell it incorrectly in order to make this work. ;-)

How Well Do These Libraries Handle the Official Specification?

I have done some testing on some existing examples that use HTML5 forms to ensure that it works the way developers expect. Here are a few examples that I have taken, with the necessary JavaScript added:
However, the HTML5 Forms specification is large, and unfortunately, the webforms2 and html5Widgets libraries don’t implement everything … yet!!!! Since I am really motivated with what HTML5 forms can do, I am committed to completing support to most, if not all, of the HTML5 Forms specification. The version of webforms2 in this blog post has been modified from Weston Ruter’s original verison, but it will be merged with the official Google Code version in the next week or so and will include compressed versions of all the library. The html5Widgets library will also have a permanent home there.
Things that I will be working on in the near future are:
  • Support for other HTML5 form elements, among other things, datalist, number, keygen, progress, time and meter
  • Support for CSS styling of HTML5 form widgets as well as the ability to style form fields according to their validation state (e.g. :valid and :invalid psudo-classes). Opera seems to be the only browser currently supporting this.
  • Default styling for some of the new input types, like tel, email, url. Opera for Mac and Opera Mobile are the only browsers I know of that support this for email and url.
    email and url form fields in Opera Mac
    email and url form fields in Opera Mac
  • Support for customizing the validation look and feel. This is one I would love to do, since I’m sure a lot of developers would want to change how validation errors appear on the screen. Unfortunately, the HTML5 specification doesn’t describe a standard way of doing this. It will be interesting to see how the browser manufacturers deal with this issue (To any browser developer reading this is working on the display form validation errors: I would love to know how you are doing this if you are willing to share. Hint, HINT! ;-))
  • In Internet Explorer 7 and lower, the ability to style input types it doesn’t support natively with CSS code like input[type="range"]
  • Enabling HTML5 forms validation on the server side to ensure data integrity for browser that don’t support HTML5 forms that have JavaScript disabled.
  • Support for internationalization of the error messages used in webforms2. If anyone wants to help in the translation of these error messages, please drop me a line — I need help!
Below is a modified version of the Wikipedia’s HTML5 forms compatibility table and see what how things the support situation stands today.
Trident Gecko WebKit Presto
Attributes
autocomplete Yes Yes Yes 2.0
list No No No 2.0
required Yes (with webforms2) Yes (with webforms2) Yes (with webforms2) 2.0
multiple No 1.9.2 526 No
pattern Yes (with webforms2) Yes (with webforms2) Yes (with webforms2, and natively in Nightly build) 2.0
min, max Yes (with webforms2) Yes (with webforms2) Yes (with webforms2) 2.0
step Yes (with webforms2) Yes (with webforms2) Yes (with webforms2 and Nightly build natively) 2.0
placeholder Yes (with webforms2) 1.9.3 Yes Yes (with webforms2)
form No 1.9.3 No 2.0
autofocus Yes (with html5Widgets) 1.9.3 Yes (with html5Widgets and Nightly build natively) 2.0
maxlength No 1.9.3 Nightly build 2.0
novalidate No No Nightly build No
control No 1.9.3 No No
accept No 1.9.3 No No
formtarget No No No No
formaction No No No No
Elements
datalist No No No 2.0
keygen No 1.0 125 1.0
output No 1.9.3 No 2.0
progress No No Nightly build No
meter No No No No
Input types
search No 1.9.3 312 No
tel No 1.9.3 Nightly build No
url No No Nightly build 2.0
email No No Nightly build 2.0
datetime Yes (with html5Widgets) Yes (with html5Widgets) Yes (with html5Widgets and Nightly build natively) 2.0
date
month
week
time
datetime-local
number No No Nightly build 2.0
range Yes (with html5Widgets) Yes (with html5Widgets) Yes 2.0
color Yes (with html5Widgets) Yes (with html5Widgets) Yes (with html5Widgets and Nightly build natively) Yes (with html5Widgets)

Integrating With visibleIf To Make Even Cooler Looking Forms

The webforms2 and html5Widgets libraries are designed to co-exist well with visibleIf to create interactive forms with fields that only validate the ones that visibleIf is displaying.
See an example of HTML5 validation working with the visibleIf JavaScript library

Acknowledgments, Shout-outs and Kudos

Further Reading

Download


This archive is the temporary home for html5Widgets. It will soon be hosted at the webforms2 Google Code page.
Both html5Widgets and webforms2 both have permanent homes at github (however, the html5Widgets github page contains a copy of webforms2 in it for your convenience). Weston Ruter has been kind to give me deciding rights over the destiny of this code. I will be updating webforms2 in the near future.
Download the latest version of html5Widgets, which includes webforms2, from github.

Web Design Trends in 2012 Tips

Pages

Online Users