2

Is there a straightforward way of creating a GUID or some other type of unique identifier within a Twig Template?

I'm aware of StringHelper.UUID (mentioned in a different question), but it doesn't look like I can use it directly in a template.

I'm comfortable creating a small plugin to expose this, or alternatively creating a twig filter to use a relevant PHP method, I just didn't want to go re-inventing the wheel if there's already a good solution I don't know about.

  • Do you need an actual GUID, or will something unique on the page suffice? – megatrond Jul 23 '15 at 17:23
  • It did need to be something unique, but not necessarily a GUID. I went with a solution similar to what Marion suggested with a combination of date and random twig filters. – Steve Holland Jul 24 '15 at 6:56
3

If a simple timestamp is unique enough, you can use:

{{ now|date('YmdHis') }}

Which will give you something like:

20150723170500
  • 2
    Similarly, date('U') will output a Unix timestamp. And if I remember correctly, lowercase u outputs microseconds. – Lindsey D Jul 23 '15 at 17:21
1

If you truly need a GUID, then a small plugin that adds it's own Twig extension can add a {{ getUUID() }} method that would look like this:

public function getUUID()
{
    return StringHelper::UUID();
}

Or for other random strings, {{ getRandomString(12, true) }}:

public function getRandomString($length = 36, $extendedChars = false)
{
    return StringHelper::randomString($length, $extendedChars);
}
  • Thanks Brad. In the end I went with a solution similar to what Marion suggested with a combination of date and random twig filters just for simplicity. – Steve Holland Jul 24 '15 at 6:57

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.