2

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:

6e6d5618f8ab8a302a236eac07c59300

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

4

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:

<?php
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!

3
  • 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 '15 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 '15 at 19:45
  • Nice! Seems a cleaner than using the variable route in my answer. Feb 14 '15 at 19:48
1

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.