<p>You can create a unique ID function in PHP and pass it to Twig</p>

<pre class="lang-twig prettyprint-override"><code>{% set uniqueId = uniqueId() %}
</code></pre>

<p>And your PHP part</p>

<pre class="lang-PHP prettyprint-override"><code>class Extension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{
    public $uniqueIds;

    public function getFunctions(): array
    {
        return [
             new Twig_SimpleFunction('uniqueId', [$this, 'getUniqueId'])
        ];
    }

    /**
     * getUniqueId
     *
     * @return string
     */
    public function getUniqueId(): string 
    {
        // generate a random string
        $id = StringHelper::randomString('12');

        // check if it's already set
        while (\in_array($id, $this-&gt;uniqueIds, true)){
            // if so, use another one
            $id = StringHelper::randomString('12');
        }
        // set it as "used"
        $this-&gt;uniqueIds[] = $id;

        return $id;
    }
}
</code></pre>

CC BY-SA 4.0
2019-02-25T23:32:33.340Z
I was thinking of some Twig only Solution, but this is also useful - thanks!
Piotr Pogorzelski
CC BY-SA 4.0
2019-06-04T14:12:42.323Z
where would this php file sit in Craft's folder structure?
erwinheiser
CC BY-SA 4.0
2019-06-04T14:20:20.707Z
Where ever you like. Craft doesn't make any assumptions about your custom folder structure. You need to include your files to your composer and register your Twig extension via module/plugin but you can place them where you like. There is no strict path as in Craft 2.
Robin Schambach
CC BY-SA 4.0
2019-02-25T09:29:47.487Z
2019-02-25T09:29:47.487Z
Robin Schambach
<p>I am not an expert in Craft CMS, but an available native solution in Twig is <code>random()</code></p>
<pre><code>{{ random() }} {# example output: 15386094 (works as the native PHP mt_rand function) #}
</code></pre>
<p>More info in the official <a href="https://twig.symfony.com/doc/3.x/functions/random.html" rel="nofollow noreferrer">twig documentation page</a>.</p>

CC BY-SA 4.0
2021-05-15T08:04:42.543Z
Wouldnt this potentially output same number multiple times? Miniscule chance, but possible.
Piotr Pogorzelski
CC BY-SA 4.0
2021-12-13T15:48:10.473Z
It could be, since it looks is not cryptographically safe
Alberto Sanchez Gonzalez
CC BY-SA 4.0
2021-05-14T16:09:03.510Z
2021-05-14T16:09:03.510Z
Alberto Sanchez Gonzalez
<p>When I include specific Twig template component multiple times, how can I give it a unique ID (or class)? </p>

<p>Components are not inside <code>for</code> loop, so I cannot use <code>loop.index</code>. I also don't wont to pass unique variable myself when I include it. And using <code>random</code> Twig function doesn't ensure that the result is unique. </p>

<p>Let's also assume that each component doesn't have unique Craft element assigned to it, like entry - in such case, I could just use this entry ID.</p>

CC BY-SA 4.0
2019-02-25T08:58:09.530Z
Could you be a bit more specific with what sort of data you are working with? Personally this is not something I have ever needed to do whilst working with Craft and Twig. That isn't to say that your use case isn't valid, but I can't quite picture what you need this for.
Jamie Wade
CC BY-SA 4.0
2019-02-25T19:12:44.283Z
@JamieWadeI can't give you anything specific, because there isn't any use case I'm thinking of now. When I create "page builder" using matrix field, templates of specific blocks of matrix can have JS included in them. And I want this JS to work only on specific instance of block, no other blocks. So naturally, I use matrix element block ID to give unique HTML attribute to div and then I run javascript using that unique attribute. I was just wondering how to do such a thing where there is no unique ID available that comes from Craft elements.
Piotr Pogorzelski
CC BY-SA 4.0
2019-02-26T09:11:48.207Z
Interesting, thanks for explaining! Looks like Robin has solved this for you anyway :-)
Jamie Wade
<templating>
Give included twig component unique ID
# Give included twig component unique ID

(Asked by: username_0 on 2019-02-25)

When I include specific Twig template component multiple times, how can I give it a unique ID (or class)?

Components are not inside `for` loop, so I cannot use `loop.index`. I also don't wont to pass unique variable myself when I include it. And using `random` Twig function doesn't ensure that the result is unique.

Let's also assume that each component doesn't have unique Craft element assigned to it, like entry - in such case, I could just use this entry ID.

**Tags:** templating

> **Comments:**
> **username_1**: Could you be a bit more specific with what sort of data you are working with? Personally this is not something I have ever needed to do whilst working with Craft and Twig. That isn't to say that your use case isn't valid, but I can't quite picture what you need this for.  
> **username_0**: @JamieWadeI can't give you anything specific, because there isn't any use case I'm thinking of now. When I create "page builder" using matrix field, templates of specific blocks of matrix can have JS included in them. And I want this JS to work only on specific instance of block, no other blocks. So naturally, I use matrix element block ID to give unique HTML attribute to div and then I run javascript using that unique attribute. I was just wondering how to do such a thing where there is no unique ID available that comes from Craft elements.  
> **username_1**: Interesting, thanks for explaining! Looks like Robin has solved this for you anyway :-)  

---

## 2 answers

### Answer by username_2 on 2019-02-25. Score: 3 | Accepted answer

You can create a unique ID function in PHP and pass it to Twig
{% set uniqueId = uniqueId() %}

And your PHP part
class Extension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{
    public $uniqueIds;

    public function getFunctions(): array
    {
        return [
             new Twig_SimpleFunction('uniqueId', [$this, 'getUniqueId'])
        ];
    }

    /**
     * getUniqueId
     *
     * @return string
     */
    public function getUniqueId(): string 
    {
        // generate a random string
        $id = StringHelper::randomString('12');

        // check if it's already set
        while (\in_array($id, $this->uniqueIds, true)){
            // if so, use another one
            $id = StringHelper::randomString('12');
        }
        // set it as "used"
        $this->uniqueIds[] = $id;

        return $id;
    }
}

> **Comments:**
> **username_0**: I was thinking of some Twig only Solution, but this is also useful - thanks!  
> **username_3**: where would this php file sit in Craft's folder structure?  
> **username_2**: Where ever you like. Craft doesn't make any assumptions about your custom folder structure. You need to include your files to your composer and register your Twig extension via module/plugin but you can place them where you like. There is no strict path as in Craft 2.  

---

### Answer by username_4 on 2021-05-14. Score: 1

I am not an expert in Craft CMS, but an available native solution in Twig is random()
{{ random() }} {# example output: 15386094 (works as the native PHP mt_rand function) #}

More info in the official twig documentation page.

> **Comments:**
> **username_0**: Wouldnt this potentially output same number multiple times? Miniscule chance, but possible.  
> **username_4**: It could be, since it looks is not cryptographically safe  

---

