Share your knowledge and create a knowledgebase.

Archive for March, 2008


Deeper look into Friendfeed API

Mar 26, 2008 Author: Ashish | Filed under: Industry News

FriendFeed is the new hotness and many people have asked for an API to take the service to the next level. There aren’t any example apps built yet, nor has there been much developer feedback yet. A whole lot of things just became possible, though.

As for technical details: FriendFeed is first releasing Python and PHP libraries, there’s an undisclosed access limit and oAuth authentication is "coming soon" (we hope so).

If you’re less than on fire about APIs and their potential - check out our post called APIs and Developer Platforms, A Discussion of the Pros and Cons - and know that 16 of the 18 authorities quoted in that post were interviewed entirely through a 3rd party Twitter client using that API.

If you’re a Twitter user you know how essential to Twitter that company’s API has become, an estimated 80% or more of Twitter use comes in through the API and the constellation of 3rd party services that leverage it. The FriendFeed API may be the most eagerly awaited since Twitter’s

This Aint Just RSS Readin’

Casual users should take note that FriendFeed is far more than just an RSS aggregator. Check out the podcast and transcript of our interview with the company’s founders in early February for details. See also my recent interview with RSS keystone Dave Winer, where we discussed FriendFeed more than anything else. You’d have seen it already if you were my friend on FriendFeed.

Commenting, feed and item display, liked-by-a-friend item exposure and a smooth friend recommendation path are some of the key differentiators of FriendFeed. In February at least, only 70% of the feeds coming into FF were RSS feeds, too. The rest are from other kinds of 3rd party APIs that the FriendFeed team has tied into by hand. There are many different Lifestreaming apps, but FriendFeed has a lot of momentum, a good user experience, renders well on mobile and has caught peoples’ imaginations. It’s also got some heavyweight backers.
The Possibilities

Some of the examples from the FriendFeed announcement are these:
"[The API is] designed to make it possible for anyone to improve FriendFeed or integrate FriendFeed into other applications. You can develop a FriendFeed interface for a mobile phone, build a FriendFeed widget for your blog, or develop an application that makes it easy to post photos to your feed from your iPhone."

I’m cheering for an Adobe AIR desktop interface, APML import/export and some sophisticated item-level recommendations. How about a FriendFeed/Imeem mashup? I’d love to listen to a streaming radio station of all the music that my FriendFeed friends favorite on their respective music networks. Oh the possibilities are many. This is a very exciting announcement.

Requests and Data Formats

All requests to the FriendFeed API are simple HTTP GET and POST requests. For example, you can fetch the JSON version of the most recent 30 public entries published to FriendFeed by fetching http://friendfeed.com/api/feed/public.

All of the API requests that output feeds are available in four formats: JSON, a simple form of XML, RSS 2.0, and Atom 1.0. JSON is the default output format. To request a different output format, simply add an format= argument to the URL:

    * http://friendfeed.com/api/feed/public?format=json
    * http://friendfeed.com/api/feed/public?format=xml
    * http://friendfeed.com/api/feed/public?format=rss
    * http://friendfeed.com/api/feed/public?format=atom

The other API requests, like posting a new comment on an entry, only support the JSON and XML output formats since they do not output feed-oriented data.

Authentication

If you are publishing data to FriendFeed or if you are requesting the feed that includes data from a user with a private feed, your HTTP requests must be authenticated.

All FriendFeed users have a Remote Key to provide third party applications access to their FriendFeed. A FriendFeed Remote Key is just like a password, except that it is only used for third party applications, so it only provides access to the functionality defined by the API. Users can easily reset it if a third party application abuses the API.

All requests that require authentication use HTTP Basic Authentication. The username should be the user’s nickname, and the password should be the user’s Remote Key. You can direct user’s to http://friendfeed.com/remotekey to get their remote key if they have not memorized it. See the FriendFeed API Application Guidelines for a complete set of recommendations of how to present authentication in your application.

The Python and PHP libraries available at http://code.google.com/p/friendfeed-api/ implement authentication for all methods that require it.

Remote Key

A remote key is a kind of password that you can give to third-party applications and websites to let them interact with FriendFeed on your behalf. There are limits to what can be done using a remote key, which means it’s a lot safer than giving a site your FriendFeed password.

JSON Callbacks

The JSON output format supports an additional argument callback= that wraps the JSON output in a function call to a function of your choice. This functionality is available to enable you to use the API with JavaScript within a web browser. For example, http://friendfeed.com/api/feed/public?callback=foo outputs:

foo({"entries":[...]})

Using JSON and callbacks, you can place the FriendFeed API request inside a <script> tag, and operate on the results with a function elsewhere in the JavaScript code on the page.

All authentication is ignored if the callback= argument is given, so JSON callbacks only work with public feeds.

Reading FriendFeed Feeds
Overview
Feed Formats

The JSON form of the feeds has the following structure:

    * entries[]
          o id - the FriendFeed entry UUID, used to add comments/likes to the entry
          o title
          o link
          o published
          o updated
          o user{} - the user who shared this entry
                + id - the user’s FriendFeed UUID
                + nickname - the user’s FriendFeed nickname, used in FriendFeed URLs
                + profileUrl - the user’s profile URL on FriendFeed
          o service{} - the service from which the entry came
                + id - the service’s FriendFeed ID, e.g., "picasa"
                + name - the service’s official name, e.g., "Picasa Web Albums"
                + profileUrl - the user’s profile URL on this service
          o comments[]
                + date
                + user{} - same structure as the user{} structure above
                + body - the textual body of the comment
          o likes[]
                + date
                + user{} - same structure as the user{} structure above
          o media[] - the videos/images associated with the entry
                + title? - the title of the media file
                + player? - the player for this media file (e.g., the YouTube.com URL with the embedded video)
                + thumbnails[] - the thumbnails for this media file
                      # url
                      # width
                      # height
                + content[] - the different versions of the media file
                      # url
                      # type - the MIME type of the media file
                      # width
                      # height

The simple XML format (output=xml) has the same structure as the JSON. The RSS and Atom formats use the standard RSS and Atom attributes for title, link, published, and updated, and include extension elements for all of the other meta-data.

Dates in JSON and dates in the FriendFeed extension elements in the Atom and RSS feeds are in RFC 3339 format in UTC. You can parse them with the strptime string "%Y-%m-%dT%H:%M:%SZ".

Filtering & Paging

All of the feed methods below support the following additional arguments:

    * service - only return entries from the service with the given ID, e.g., service=twitter
    * start - return entries starting with the given index, e.g., start=30
    * num - return num entries starting from start, e.g., num=10

Methods

/api/feed/public - Fetch all Public Entries

Returns the most recent public entries on FriendFeed:

http://friendfeed.com/api/feed/public

Using the FriendFeed Python library:

service = friendfeed.FriendFeed()
feed = service.fetch_public_feed()
for entry in feed["entries"]:
    print entry["title"]

/api/feed/user/NICKNAME - Fetch Entries from a User

Returns the most recent entries from the user with the given nickname:

http://friendfeed.com/api/feed/user/bret

If the user has a private feed, authentication is required.

Using the FriendFeed Python library:

service = friendfeed.FriendFeed()
feed = service.fetch_user_feed("bret")
for entry in feed["entries"]:
    print entry["title"]

/api/feed/user/NICKNAME/comments - Fetch Entries a User Has Commented On

Returns the most recent entries the user has commented on, ordered by the date of that user’s comments:

http://friendfeed.com/api/feed/user/bret/comments

If the user has a private feed, authentication is required.
/api/feed/user/NICKNAME/likes - Fetch Entries a User Has "Liked"

Returns the most recent entries the user has "liked," ordered by the date of that user’s "likes":

http://friendfeed.com/api/feed/user/bret/likes

If the user has a private feed, authentication is required.
/api/feed/user/NICKNAME/discussion - Fetch Entries a User Has Commented On or "Liked"

Returns the most recent entries the user has commented on or "liked":

http://friendfeed.com/api/feed/user/bret/discussion

If the user has a private feed, authentication is required.
/api/feed/user - Fetch Entries from Multiple Users

Returns the most recent entries from a list of users, specified by nickname:

http://friendfeed.com/api/feed/user?nickname=bret,paul,jim

If more than one nickname is specified, the feed most recent entries from all of the given users. If any one of the users has a private feed, authentication is required.

Using the FriendFeed Python library:

service = friendfeed.FriendFeed()
feed = service.fetch_multi_user_feed(["bret", "jim", "paul"])
for entry in feed["entries"]:
    print entry["title"]

/api/feed/home - Fetch the Friends Feed

Returns the entries the authenticated user would see on their FriendFeed homepage - all of their subscriptions and friend-of-a-friend entries:

http://friendfeed.com/api/feed/home

Authentication is always required.

Using the FriendFeed Python library:

service = friendfeed.FriendFeed(nickname, remote_key)
feed = service.fetch_home_feed()
for entry in feed["entries"]:
    print entry["title"]

/api/feed/search - Search

Executes a search over the entries in FriendFeed. If the request is authenticated, the default scope is over all of the entries in the authenticated user’s Friends Feed. If the request is not authenticated, the default scope is over all public entries.

http://friendfeed.com/api/feed/search?q=friendfeed

The query syntax is the same syntax as http://friendfeed.com/search/advanced. The query operators are:

    * who: -restricts the search to a specific user, e.g., who:bret
    * service: restricts the search to a specific service ID, e.g., service:twitter

Using the FriendFeed Python library:

service = friendfeed.FriendFeed()
feed = service.search("who:bret friendfeed")
for entry in feed["entries"]:
    print entry["title"]

Publishing To FriendFeed

All of the calls to publish information to FriendFeed are HTTP requests. You can perform test calls from a web browser using the HTTP Basic Authentication built into your browser at http://friendfeed.com/static/html/apitest.html.

Requests to FriendFeed are rate limited, which, e.g., limits the number and size of thumbnails you can upload in a day. Normal uses should fall well within our rate limits. If you encounter HTTP 403 errors because of rate limits, and you think the limit is erroneous, please let us know in the developer forum.

Create New Entries
/api/share - Publish Links or Messages

A POST request to /api/share will publish a new entry on the authenticated user’s feed. The arguments are:

    * title - required - The text of the new entry.
    * link - The URL of the new entry. If it is not specified, the new entry will look like a quoted message. If specified, it will look like a link.
    * comment - If specified, the given text is posted as a comment under the new entry.
    * imageN_url, imageN_link - The thumbnail images for the entry, specified from a 0-based index. image0_url specifies the URL of the image, which will be resized to the maximum size of a thumbnail and stored on FriendFeed’s servers. If image0_link is not given, the thumbnail will link to the main link URL. If it is specified, the thumbnail will link to the specified image0_link.

Example usage with the FriendFeed Python library:

service = friendfeed.FriendFeed(nickname, remote_key)

# Publish a text message
service.publish_message("Testing the FriendFeed API")

# Publish a link
service.publish_link("Testing the FriendFeed API", "http://friendfeed.com/api/")

# Publish a link with thumbnail images
service.publish_link(
    title="Testing the FriendFeed API",
    link="http://friendfeed.com/api/",
    image_urls=[
        "http://friendfeed.com/static/images/jim-superman.jpg",
        "http://friendfeed.com/static/images/logo.png",
    ],
)

Example usage with curl:

curl -u "nickname:remotekey" -d "title=Testing+the+FriendFeed+API&link=http://friendfeed.com/" http://friendfeed.com/api/share

Upload Images with Entries

The /api/share method can also accept uploaded images encoded as multipart/form-data. This encoding is the standard used for file uploads within web browsers.

If any images are uploaded with the /api/share request, the original and the thumbnail are stored on FriendFeed’s servers, and the thumbnail is displayed with the entry.

By default, the thumbnails will link to the destination link for the entry. If you want each uploaded image to link somewhere else, you can specify the link in the IMAGENAME_link argument. For example, if your uploaded image is POST argument file0, you can specify the link for that thumbnail as file0_link.

Comment and Like Entries
/api/comment - Add or Edit Comments

A POST request to /feed/comment will add a comment or edit an existing comment on a FriendFeed entry. The arguments are:

    * entry - required - The FriendFeed UUID of the entry to which this comment is attached.
    * body - required - The textual body of the comment.
    * comment - If given, the FriendFeed UUID of the comment to edit. If not given, the request will create a new comment.

Example usage from the Python library:

service = friendfeed.FriendFeed(nickname, remote_key)
service.add_comment(
    entry="550e8400-e29b-41d4-a716-446655440000",
    body="Testing the FriendFeed API",
)

Example usage with curl:

curl -u "nickname:remotekey" -d "entry=550e8400-e29b-41d4-a716-446655440000&body=Testing+the+FriendFeed+API" http://friendfeed.com/api/comment

/api/comment/delete - Delete a Comment

A POST request to /feed/comment/delete will delete an existing comment. The arguments are:

    * entry - required - The FriendFeed UUID of the entry to which this comment is attached.
    * comment - required - The FriendFeed UUID of the comment to delete.

/api/like - "Like" an Entry

A POST request to /feed/like will add a "Like" to a FriendFeed entry for the authenticated user.

    * entry - required - The FriendFeed UUID of the entry to which this comment is attached

Example usage from the Python library:

service = friendfeed.FriendFeed(nickname, remote_key)
service.add_like("550e8400-e29b-41d4-a716-446655440000")

Example usage with curl:

curl -u "nickname:remotekey" -d "entry=550e8400-e29b-41d4-a716-446655440000" http://friendfeed.com/api/like

/api/like/delete - Delete a "Like"

A POST request to /feed/like/delete will delete an existing "Like." The arguments are:

    * entry - required - The FriendFeed UUID of the entry to which this comment is attached.

Authentication

If your application requires authentication, you use the following terminology FriendFeed nickname or email and Remote key in your login form. Your login form should contain a link to http://friendfeed.com/remotekey for users who have not memorized their key. It should open in a new window using target="_blank" so that the remote key page does not interrupt your application’s flow.

Implementing Websites For Internationalization

Mar 24, 2008 Author: admin | Filed under: Java

Most business in today’s open market are demanding their websites & web application to have multilingual support. This is in order to attract non-English speaking audiences to increase their customer base and make people comfortable using the application in their native language. But for this, it would require an existing business application to be customized to support native locale. The process of producing an application that can be localized for a particular country without any changes to the program code is called Internationalization.

Internationalization

Following are the list of things one needs to take care while making an application to implement Internationalization.

1. Producing Content in Unicode

You need to make sure that all files which contain the multilingual content are in Unicode format. By default most text editors will store your file in ASCII which does not support other language characters. So after saving any content in ASCII format and loading it, your browser might not be able to display correct text in native language. Here you need to convert the file from ASCII to UTF format.

For example, the steps required for doing this if you are using Notepad are,

    * Open your JavaScript or properties, etc. file in notepad
    * Go to > File > Save As > Encoding
    * Change Encoding from ASCII to UTF-8

2. Files needed to be converted to UTF

.properties

All your properties file should have a suffix based on the language in which the content is stored in this file. For example,

    * For English, content_en.properties for French content_fr.properties and so on.
    * Most java frameworks like Struts, Spring have inbuilt support to detect JVM locale and select the corresponding properties file based on the extension of the file & JVM/Browser setting. You don’t need to add any code to detect the setting and set the properties file

.java

Make sure that your JVM has set the parameter -Dfile.encoding=UTF-8

.js

Set charset attribute of the SCRIPT tag to “UTF-8″. For example,

    <script type=”text/javascript” src=”./urscript.js” charset=”UTF-8″></script>

.xml

Use the steps as in the first example to make sure the content within the XML files in is UTF-8 format.

.html/.htm

Add this line to head of all html pages.

    <meta name=”http-equiv” content=”Content-type: text/html; charset=UTF-8“/>

.jsp

Set Content-type explicitly through your server side scripts. To do this, add this line to all your jsp pages,

    <%@page contentType=”text/html; charset=UTF-8” pageEncoding=”UTF-8″%>

3. Configuring the Web Server

Your Web Server has to be configured to set the Content-type of headers to UTF-8 since by default the web server will replace the Content-type-header to ISO-8859 encoding. For example:

    * In Apache Web Server, edit httpd.conf to set AddDefaultCharset=Off.
    * In Tomcat Server set connector settings within the server.xml file to URIEncoding=”UTF-8″

4. Handling Request & Response Objects

Make sure that before reading request parameters & writing to response objects set character encoding type to UTF-8. This can be handled using filters where all the contents coming in and going out can be set to UTF-8 encoding. For example,

    * request.setCharacterEncoding(”UTF-8″);
    * response.setContentType(”text/html”);
    * response.setCharacterEncoding(”UTF-8″);

5. Creating Database with Unicode encoding

While using a database make sure that the database created has encoding set to UNICODE. Most of the database servers like Oracle, Postgress, MySQL and MSSQL have this support. In order to create databases with unicode encoding use the following query,

    CREATE DATABASE MyWebApps DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

Once all the above steps are implemented your web application will work smoothly for all UTF-8 supported languages.

Mozilla is on a spree to revolutionize the way we use web applications today, just like Mozilla WebRunner. Naming it as a killer app just wasn’t doing justice to it. So I felt an urge to bring to the notice that it isn’t just any other app.It will be, probably the next biggest thing that the web will be seeing after Ajax.

Ajax had redefined the web application just a couple of years ago. It definitely changed in the way web apps were being developed. This promoted rise of different interesting possibilities that more than widened the eyeball of a regular surfer. Web Operating Systems were at that time being touted as being able to replace the desktop operating system altogether in the future. But all these breath taking ideas have fallen flat to a place where the idea is still traditional. The usage of web browser.

Web applications have and still are web applications and I have not come upon any idea so simple yet so revolutionizing as the WebRunner. To update you upon the news surrounding WebRunner, Mozilla has converted the WebRunner project to a Mozilla Labs Project with a new fascinating name, Prism. When I saw Web Runner I was not amazed at this app itself. My mind was already seeing the future of web applications. It’s behavior was similar to the nature of a desktop application. Yet it ran on the web! It was the perfect example of how we can expect to put our web applications for our future projects.

Mozilla Prism

I think I may be a little too far a bit sooner, but I can see how Prism an impact our surfing lives. Imagine a day, you start your computer in just a moment, without any startup utilities coming in the picture. You have several Prism apps lying on your desktop. You double click an application and it is launched in another moment. This is something I am dreaming of, something which will definitely be backed by todays high speed connectivity and robust network infrastructure.

Well,a question in your mind would be how would Mozilla’s Prism contribute here. The direction I am seeing for Prism is not something out of context from my dream. A lite browser without the unnecessary facilities of the browser like the back button, the menu bar, the history, the bookmarks which only matter while surfing web sites. Prism is just enough to provide the basic foundation for connecting to the web, minus the normal browser behavior, yet retaining the background services like session management and security. Web applications don’t need them and all the more should not be taken care when they are being designed.

Web Apps with Mozilla Prism

Prism comes to mind when we require a web application to work in their own self with the support of the design which the web application has itself provided and not that of the browser. This is a thing of the past where web applications are designed with a thought process of developing a web site. Kind of traditional way which considered styling, the cross browser compatibility and many other aspects which form a part of the web site and not of the web application.

With Prism I am sure that one day the project would take us to a time where web applications would not require any HTML, CSS or JavaScript. It would be just like designing a desktop application just as we do it currently in .NET and Eclipse IDE’s. Drag and drop your required widget, give a theme for the app, and execute the app in Prism and later distribute it as a web application. The users of the Prism would just have the need to Prism app installed on their system. This is just like Java where only the JVM needs to be installed and the Java Programs come to life. Similarly install Prism and the required web application will come to its life.

HTC Developing Phone for Android

Mar 21, 2008 Author: Ashish | Filed under: Google Android

High Tech Computer (HTC) is developing a mobile phone that will use the open-source Android software created by Google for its operating system. The phone will be called Dream and have a large touchscreen LucidTouch-Profile Feb-08 and full QWERTY keypad. The handset is over 5 inches long and 3 inches wide and has a keypad that swivels out from underneath the screen.htc.gif

HTC is not the only company that is developing a mobile phone around the Android operating system. Samsung has joined the hunt to create a device that utilizes Android.

HTC was the first company to announce it was building a phone around Android. Other members of the Open Handset Alliance, a group dedicated to promoting Android, are also believed to be developing handsets designed around the operating system. Over 30 companies have joined the Open handset Alliance. Samsung and Motorola are two manufactures who belong to the alliance and may be developing Android phones of their own.

PHP Templating with Smarty

Mar 21, 2008 Author: Ashish | Filed under: PHP

Smarty Overview
The theoretical web development process is that: first the designer makes the interface, and breaks it down into HTML pieces for the programmer then the programmer implements the PHP business logic into the HTML.

That’s fine in theory, but in practice, from my experience, the client frequently comes with more requirements, or maybe more modifications to the design or to the business logic. When this happens , the HTML is modified (or words rebuilt ) programmer changes the code inside HTML.

The problem with this scenario is that the programmer needs to be on stand-by until the designer completes the layout and the HTML files. Another problem is that if there is a major design change then the programmer will change the code to fit in the new page. And that’s why I recommand Smarty. Smarty is a templating engine for PHP.

You can download it from http://www.phpinsider.com/php/code/Smarty/ or http://smarty.php.net . The installation process is very simple. Just read the documentation and follow up the instructions.

So what is Smarty ? Smarty is a set of PHP classes that compile the templates into PHP scripts. Smarty is a template language and a very useful tool for designers and programmers.

Smarty for Designers

Designers work with HTML files. To work with Smarty, you work with template files. These files are are made up of static content but combined with Smarty mark-up tags. All the template files have a .tpl extension. The Smarty template tags are enclosed within { and } delimiters.

Let’s consider the basic structure of a web page. There is a header, a middle part, and a footer. A template file that includes the header and the footer looks like this:

{include file="header.tpl"}
<form name="form1">
    Label1 <input type="text" name="text1">
    <input type="submit" value="submit">
</form>
{include file="footer.tpl"}

All the templates should reside in a single template directory. After calling a template for the first time, the compiled template will reside in templates_c.

Smarty language is very poweful. All the variables that come from PHP are identified in Smarty with {$Variable_Name} (we precede them with a $ sign). So if we have a variable in PHP that is called $MyName, then to print it in Smarty you have to write something like:

<html>
    <body>
        Welcome, {$MyName} <br>
    </body>
</html>

The power of Smarty lies also in its flexibility. You can insert IFs and LOOPs into the template. The syntax for IF is:

{if <condition> }
        html code
{else}
        html code
{/if}

Let’s say you have a dynamic menu based on links. Depending on the link you click, you go to a specific page. So you get from PHP a variable $Menu with a integer value, depending on the page you are. The template looks like :

{if ($Menu == 1) }
         Option 1
{else}
        <a href="option1.php">Option 1</a>
{/if}
{if ($Menu == 2)}
        Option 2
{else}
        <a href="option2.php">Option 2</a>
{/if}

For coding a loop let’s suppose you get an array like the following from PHP :

<table>
<tr
{section name=user loop=$userID}
{if $smarty.section.user.iteration is odd}
        bgcolor=#efefef
{else}
        bgcolor=#ffffff       
{/if}
>
    <td>    ID = {$userID[user]}  </td>
    <td> Name = {$name[user]}     </td>
    <td> Address = {$address[user]} </td>
</tr>
    {sectionelse}
<tr>
    <td>
        There is no user.
    </td>
</tr>
</section>
</table>

Iteration is an internal counter for Smarty. It helps us to know the current iteration of the section. I use this internal variable to make alternate row colors in the table by checking if current iteration value is odd or not (Note that iteration was added to Smarty from version 1.4.4).

An alternative for LOOPS is FOREACH which is used to loop over a single associative array.

<foreach from=$users item=current_user>
        Name = {$current_user}
<foreachelse}
        No user available.
</foreach>

The main difference between SECTION and FOREACH is that for SECTION you can start from a specific value, and can also set a step for the iteration, whereas for FOREACH you have to loop over all values.

Smarty for Programmers

The advantage for programmers is that they write the code in a PHP file without having to mix the instructions with HTML. Furthermore, if the designer changes the layout of a page the programmer doesn’t have to change the code to suit the new layout since the functionalities won’t change. You do your work in your files, assign to the templates all the values needed to print on the site and go out for a beer. You won’t get phone calls asking you to change a bit of code because the designer changed the layout and now a set of internal errors cropped up.

In the PHP file you need to include the Smarty class require ‘Smarty.class.php’. After that you need to instantiate the smarty with $smarty = new Smarty.

To assign a variable to the template you need to $smarty->assign(’UserName’, ‘John Doe’). After everything is finished you call the method to display the template $smarty->display(’index.tpl’).

A sample code looks like this (index.php) :

<?php
require ‘Smarty.class.php’;
$smarty = new Smarty;

$smarty->assign(’Username’, ‘John Doe’);
$smarty->display(’index.tpl’);
?>

The template (index.tpl) looks like this:

<html>
<body>
        Welcome {$Username}
</body>
</html>

You can also create an array in PHP an pass it to the template:

$tmp = array ( ‘UID’=> ‘10′,  &’Name’ => ‘John Doe’, ‘Address’=>’Home address’);
$smarty->assign(’info’, $tmp);

Sample Script

This script connects to a local database and select all the products from the ‘Products’ table. Then it passes all the values to the template, which prints them on the screen.

INDEX.PHP

<?php
require ‘Smarty.class.php’;
$smarty = new Smarty;

$hostname = "localhost";
$dbUser = "sqluser";
$dbPass = "sqlpass";
$dbName = "sqldb";
// connect to the database
$conn = mysql_connect($hostname, $dbUser, $dbPass) or die("Cannot connect to the database");

mysql_select_db($dbName);

$sql = "SELECT prodID, info FROM products ORDER BY prodID ASC";
// get all the products from the table
$res = mysql_query($sql);
$results = array();
$i=0;
while ($r=mysql_fetch_array($res)) {
            $tmp = array(
                ‘prodID’ => $r['prodID'],
                ‘info’=> $r['info']
            );
            $results[$i++] = $tmp;
}
// pass the results to the template
$smarty->assign(’results’, $results);
// load the template
$smarty->display(’index.tpl’);
?>

INDEX.TPL

<html>
<body>
Here’s a table with the results: <br>
<table cellpadding=1 cellspacing=0 border=0 width=100%>
{section name=nr loop=$results}
    <tr {if $smarty.section.nr.iteration is odd} bgcolor="#efefef"{/if}>
        <td class=fb width=15%>
            <nobr><a href=&#8221;show-product.php?id={$results[nr].prodID}">Press here</a>

        <td class=fb width=29%><a href="show.php?id={$results[nr].prodID}"
        {popup inarray=$smarty.section.nr.iteration}
        >{$results[nr].info}</a></td>
    </tr>

{sectionelse}
<tr><td align="center"><br><b>no product </b> <br> </td></tr>
{/section}
   
</table>

<br>

Here’s a select with the results: <br>
<select name="mys">
    {section name=nr loop=$results}
        <option value="{$results[nr].prodID}">{$results[nr].info}</option>
    {/section}
</select>

</body>
</html>

Summary

Smarty is a great tool for both designers and developers. By using Smarty you can reduce the site development and maintenance times. If you are a developer you no longer need to mix PHP code with HTML code. Just take care of business logic and leave the HTML to the designer.

Recent Comments