Skip to content

Instantly share code, notes, and snippets.

@reatlat
Forked from hijonathan/example.html
Last active February 12, 2024 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reatlat/7962396cae306b45110b64808ec20a66 to your computer and use it in GitHub Desktop.
Save reatlat/7962396cae306b45110b64808ec20a66 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment