Last active
February 12, 2024 01:30
-
-
Save hijonathan/5db3d8ec64e267d06c32 to your computer and use it in GitHub Desktop.
Generate a unique id in a Jinja template.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
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
For example.html, add dashes to the first macro's for loop to prevent spaces from appearing between numbers
1 2 5 2 6
.