• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Few Useful Smarty Examples And Tips

Few Useful Smarty Examples And Tips

April 4, 2013 by Rana Ahsan 1 Comment

smarty tips

If you have already read my basic smarty tutorial, then it is enough to work with it and get help in small parts from the official documentation of smarty. I have been actually working this way. But, I came to realize that, often I am forgetting or having issues with some basic implementation. And searching for similar things again and again often. Thus, I have decided to make a list that will include some common smarty examples and tips so that it become a helpful for myself and hopefully for my readers as well :). Even, you may find few tips useful in such a way, you never thought possible or searched with them. But here you will learn to implement them in an efficient way. Most of the facts here are based on smarty version 3.x, which I recommend strongly. So, here we go:

Apply PHP functions On Smarty Variable:

Did you sometimes feel that you need to run some PHP functions, either core or custom that you wrote yourself on smarty variable/data? I do definitely feel often. We can do easily and I found a couple of different ways to do this kind of tasks:

  • Using {php} tag: If you are using smarty 2.x version, then you will be able to use ‘{php}{/php}’ tag to use core php code as like you do on regular php file. But, in smarty version 3.x , this has been deprecated and strongly discouraged. I also personally not a fan of this, as it may mislead to some developers to being dirty and write several PHP codes in it which a template file don’t deserve. Moreover, to me, it really breaks the meaning of using smarty.
  • Use php functions inside conditional statement: If you are using conditional statement like if and inside that you want to apply a PHP function like ‘strstr’,’empty’ etc, then you can apply it usually, without any problem. A small code example is:
    {if strstr($string1,$string2)}
        string matching found
    {/if}
    
  • Apply PHP Function On a smarty variable: Apply a php function on smarty variable can be done in the similar way as the smarty functions. Example:
    We have currently {$smarty_array_variable|count} entries in our record.
    

    Notice that, the above ‘count()’ php function takes one parameter and thus by default the smarty data is passed as so. Now, what about if a function takes two parameters? Use the same way smarty passes extra parameters as below:

    {"a long test string"|strstr:"test"}
    

Foreach Or Section, Which To Use?

Well, if you have see some basic examples, then you might get confused which one to use in what type of cases. Let me make you clear about this:

  • Most of the time, try your best to avoid ‘section’, use ‘foreach’. It is recommended officially as well.
  • ‘section’ can’t deal with associative array index. So, if you are dealing with such array, forget about using ‘section’, ‘foreach’ is your only choice.
  • Suppose you are showing a list of members, their country, city and zip code. For basic implementation, you may have retrieve those info in separate arrays like ‘$countries’,’$cities’ and ‘$zips’. Now you just loop over the members array, retrieve the country/city/zip id from each member’s data and show them. In such cases you can consider using ‘section’ ir a zip code api. If you need to use the loop data later on some purpose, like whether certain data has been shown in a loop or not, total number of loops iterated etc, then go for section, you won’t get such support in foreach by default, but will in ‘section’. See section function documentation for details.
  • If you want to loop in more incremental way , such as access only odd rows/even rows or skip every 5 data or something like that, go for ‘section’ instead of ‘foreach’ for better efficiency.

Smarty Example For Incrementing Variable Value:

In many cases, you will may need to use smarty variable, increment its value, assign to itself or to another one etc. You will be able to do so as like in the following code example:

{assign var=myvar value=1}
{assign var=myvar value=$myvar+1}
//alternative way
{assign name=myvar value=1}
{capture assign=myvar}{$myvar+1}{/capture}

Using Caching In Smarty:

Well, it is natural to use caching in smarty. The following code snippet will show you the basic caching operations.

//set cache life time to 5 minutes
$smarty->setCaching(Smarty::300);

// clear out all currently available cache
$smarty->clearAllCache();

//check whether a cache for a template available or not
$smarty->isCached('template.tpl')

If you still have some part of the template which aren’t to be cached, while smarty caching is enabled already, you can use “{nocache}{/nocache}” tag to get it worked. data shown inside this tag won’t be cached.

Write Inline JavaScript In Smarty Template:

If you wish to write some inline JavaScript functions inside a smarty template file, you won’t be able to do it straight forward, if you are using “{“/”}” symbols as these are part of smarty’s directives as well. So, what to do?

Smarty gives a handy use case for this, to simply put an extra “{literal}{/literal}” tag around your JavaScript code. Here is an example:

{literal}
<script language="javascript">
function test_method() {
   //do something
}
</script>
{/literal}

Final Words:

This is an ongoing list, I will add more in future. I hope the above mentioned smarty examples and tips will help you in some extent. If you have any suggestions/comments, question or more tips to contribute, feel free to let me know. Happy smarty programming 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: php, smarty

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. pakdhetimin says

    July 7, 2019 at 6:23 am

    thank u for your explanations. how to code in smarty when i wanna increment page view count +1 whenever the page is loaded and the incremented value is updated to mysql database, how to code that in php mysql and smarty tpl? would u help me to code this? thanks in advance

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Building Auth With JWT – Part 2
    Building Auth With JWT – Part 2
  • "Facebooksdk" - C#.NET Library For Facebook API
    "Facebooksdk" - C#.NET Library For Facebook API

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023