Zinga Zinga - 1 year ago 322
Smarty Question

How to correctly use {$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI} in Smarty?

I have a blog page in my website, which uses Smarty to create the posts, and I want to add a WhatsApp share button to them using it. I already searched on the whole internet, and I found this:


I am trying to use this right now in my blog.tpl file:

<a class="whatsapp" href="whatsapp://send?text={$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI}">Compartilhar</a>

What's wrong with my code, and how could i fix it?

Answer Source

Your code doesn't work because of several reasons:

  • The obvious one is that the message you generate is not an URL. It reads something like: stackoverflow/questions/40062450/.... An URL starts with a protocol (usually http://). The text you send should be:

  • An URL (as the one generated by the above code) contains special characters that must be encoded when it is used as an argument in another URL (f.e. &). Failing to properly encode & when you want to use it as a parameter in an URL leads to the generation of a different URL than you think. Smarty provides the escape variable modifier for this purpose.

  • You generate HTML and, because some characters are also special in HTML you have to properly encode them, otherwise the HTML you generate could be invalid and the browser could think the URL ends earlier than you intend. The escape modifier helps you here too.

Putting all together, the best way is to build the URL into a separate Smarty variable then write it into the href attribute:

  * Generate the URL we want to send using WhatsApp
  * and store it in the $url Smarty variable
  * There is no encoding here
  * --}
{capture assign=url}{strip}

 * The URL to invoke the WhatsApp app (and ask it to send $url as message) is:
 *     whatsapp://send?text={$url|escape:url}
 * --}

 * Generate correct HTML that contains the correct whatsapp URL
 * that contains as parameter the URL generated in $url
 * --}
<a class="whatsapp" href="whatsapp://send?text={$url|escape:url|escape:html}">Compartilhar</a>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download