I've been digging around and haven't found an existing Twig filter for what I'm trying to do. Basically, I'd like a filter that would provide a hash of a phrase.

Pseudo-template code would be something like this:

{{ "my phrase here"|hashwithmd5 }} 

And would generate this in my rendered template:


Does something like this exist? Am I going about this in a bad way?

2 Answers 2


sounds like a simple plugin will do the trick for you. You will need to set up your main plugin class and a variable class.

Your variable class will look something like this:

namespace Craft;

class YourPluginNameVariable
    public function makeHash($string)
        $hashed = md5($string);
        return $hashed;

You can call this in your templates like this:

{{craft.yourpluginname.makeHash('my phrase here')}}

Hope this helps!

  • That's what I thought I might need to do. Just didn't want to reinvent the wheel if I didn't need to. Thank you! Feb 14, 2015 at 19:05
  • 1
    I wrote one quickly and have posted it to my GitHub page: github.com/johnfmorton/Craft-MD5-Twig-Filter-Plugin You use it like {{ "my phrase here" | toMd5 }} Feb 14, 2015 at 19:45
  • Nice! Seems a cleaner than using the variable route in my answer. Feb 14, 2015 at 19:48

Hope this helps:

I needed a hash that only changed if the resource file is modified thus allowing reliable caching.

Usage: <img src="{{ hash('/images/my_image.jpg') }}"

Can be used for javascript, css or an image resource.

// src/Twig/appExtension.php
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
    public function getFunctions()
        return [
            new TwigFunction('hash', [$this, 'hash'])

    // add hash to resource
    public function hash($filename)
        $filepath = getcwd() . $filename;
        $md5 = md5_file($filepath);
        return $filename . "?hash=" . $md5;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.