Skip to content

Instantly share code, notes, and snippets.

@rayfranco
Last active November 6, 2018 05:30
Show Gist options
  • Save rayfranco/4526940 to your computer and use it in GitHub Desktop.
Save rayfranco/4526940 to your computer and use it in GitHub Desktop.
Twig extension filter that convert email into gravatar url, or secure gravatar url
# config.yml
services:
acme.twig.gravatar_extension:
class: Ray\CoreBundle\Twig\GravatarExtension
tags:
- { name: twig.extension }
<?php
// Acme\DemoBundle\Twig\GravatarExtension
namespace Acme\DemoBundle\Twig;
class GravatarExtension extends \Twig_Extension
{
private $secure_request = false;
public function getFilters()
{
return array(
'gravatar' => new \Twig_Filter_Method($this, 'gravatarFilter'),
'sgravatar' => new \Twig_Filter_Method($this, 'secureGravatarFilter'),
);
}
public function gravatarFilter($email, $size = null, $default = null)
{
$defaults = array(
'404',
'mm',
'identicon',
'monsterid',
'wavatar',
'retro',
'blank'
);
$hash = md5($email);
$url = $this->secure_request ? 'https://' : 'http://';
$url .= 'www.gravatar.com/avatar/'.$hash;
// Size
if (!is_null($size)){
$url .= "?s=$size";
}
// Default
if (!is_null($default)){
$url .= is_null($size) ? '?' : '&';
$url .= in_array($default, $defaults) ? $default : urlencode($default);
}
return $url;
}
public function secureGravatarFilter($email, $size = null, $default = null)
{
$this->secure_request = true;
}
public function getName()
{
return 'gravatar_extension';
}
}
{{ email | gravatar }} # Will return default gravatar url
{{ email | gravatar(64) }} # Will return gravatar url 64x64
{{ email | gravatar(200,'identicon') }} # Will return gravatar url 200x200 with default identicon
{{ email | sgravatar }} # Will return default secure (https) gravatar url
@andythorne
Copy link

Very useful! Looks like you're missing the parameter name from the default value though on L43:

$url .= 'd=' . (in_array($default, $defaults) ? $default : urlencode($default));

@LaurentMarquet
Copy link

Thanks!

@JulienBreux
Copy link

Thanks!

@rroose
Copy link

rroose commented Aug 19, 2016

Thanks but I'm getting the following error implementing this in Drupal:

Warning: md5() expects parameter 1 to be string, array given in Drupal\twig_gravatar\Twig\Extension\GravatarExtension->gravatarFilter() (line 29 of modules/twig_gravatar/src/Twig/Extension/GravatarExtension.php).

Line 29 is:

$hash = md5($email);

@lunfel
Copy link

lunfel commented Sep 19, 2016

@rroose it may seem that the data your applying the filter on in your twig template is an array.

{{ email | gravatar }} The email data should be a string here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment