Skip to content

Instantly share code, notes, and snippets.

@hijonathan
Last active February 12, 2024 01:30
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hijonathan/5db3d8ec64e267d06c32 to your computer and use it in GitHub Desktop.
Save hijonathan/5db3d8ec64e267d06c32 to your computer and use it in GitHub Desktop.
Generate a unique id in a Jinja template.
<!-- Jinja Unique ID Generator -->
{% macro random_int(len) -%}
{% for n in range(len) %}
{{ [0,1,2,3,4,5,6,7,8,9]|random }}
{% endfor %}
{%- endmacro %}
{% macro unique_id(count_groups=5, group_len=6, separator='-') -%}
{% set parts %}
{% for n in range(count_groups) -%}
{{ random_int(group_len) }}
{% endfor %}
{% endset %}
{{ parts|join(separator) }}
{%- endmacro %}
<!-- Usage: -->
<p>Here's a simple id: {{ unique_id() }}</p>
<p>Here's a really long id: {{ unique_id(100, 10, '_'}}</p>
<!-- Jinja Unique ID Generator: HubSpot COS version. -->
<!-- HubSpot's COS doesn't support all of Jinja, so you have to do things manually. -->
<!-- HubSpot doesn't escape whitespace. -->
{% macro random_int() %}{% for n in [0,1,2,3,4,5] %}{{ [0,1,2,3,4,5,6,7,8,9]|random }}{% endfor %}{% endmacro %}
<!-- You have to manually call the macros in a list. -->
{% set parts = [random_int(), random_int(), random_int(), random_int(), random_int()] %}
{% set unique_id = parts|join('-') %}
<!--
This is really handy for uniquely identifying a global module in HubSpot, especially when you need to pass that info around to a script.
In this example, the unique ID helps identify only the form that's used in this global module.
-->
<script>
// jQuery for simplity here.
$(function() {
$('form#' + {{ unique_id }}).on('submit', function() {
console.log('Form submitted.', this);
});
});
</script>
<form id='{{ unique_id }}'>
<input type='submit' value='Submit me'>
</form>
@MichaelCurrin
Copy link

For example.html, add dashes to the first macro's for loop to prevent spaces from appearing between numbers 1 2 5 2 6.

{%- macro random_int(len) -%}
  {%- for _ in range(len) -%}
    {{ range(10) | random }}
  {%- endfor -%}
{%- endmacro -%}
random_int(10)
1473624976

@jfthuong
Copy link

In example.html, there is a missing ):

<p>Here's a really long id: {{ unique_id(100, 10, '_'}}</p>

should be

<p>Here's a really long id: {{ unique_id(100, 10, '_') }}</p>

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