Skip to content

Commit

Permalink
Add encode / decode methods in twig template
Browse files Browse the repository at this point in the history
  • Loading branch information
stephledev authored and roukmoute committed Mar 12, 2017
1 parent 0a66044 commit 95f01ee
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,12 @@ public function getAction(User $user)
As you can see, the autowiring feature reduces the amount of
configuration required to define a hashid.

# Twig Extension
## Usage
```twig
{{ path('users.show', {'hashid': user.id | hashids_encode }) }}
{{ app.request.query.get('hashid') | hashids_decode }}
```

[1]: https://github.com/ivanakimov/hashids.php
[2]: http://hashids.org/php/
5 changes: 5 additions & 0 deletions Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,10 @@
<argument>%hashids.autowire%</argument>
<tag name="request.param_converter" priority="1" converter="hashids.converter" />
</service>

<service id="hashids.twig.extension" class="Roukmoute\HashidsBundle\Twig\HashidsExtension">
<argument type="service" id="hashids" />
<tag name="twig.extension" />
</service>
</services>
</container>
42 changes: 42 additions & 0 deletions src/Twig/HashidsExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace Roukmoute\HashidsBundle\Twig;

use Roukmoute\HashidsBundle\Hashids;

class HashidsExtension extends \Twig_Extension
{
/**
* @var Hashids
*/
private $hashids;

public function __construct(Hashids $hashids)
{
$this->hashids = $hashids;
}

public function getFilters()
{
return [
new \Twig_SimpleFilter('hashids_encode', [$this, 'encode']),
new \Twig_SimpleFilter('hashids_decode', [$this, 'decode']),
];
}

public function getName()
{
return 'hashids_extension';
}

public function encode($number)
{
return $this->hashids->encode($number);
}

public function decode($hash)
{
return $this->hashids->decode($hash);
}

}

0 comments on commit 95f01ee

Please sign in to comment.