Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created May 20, 2022 15:09
Show Gist options
  • Save bartwttewaall/06149eb18f6d211bd9d0f5e957d3f030 to your computer and use it in GitHub Desktop.
Save bartwttewaall/06149eb18f6d211bd9d0f5e957d3f030 to your computer and use it in GitHub Desktop.
Hubspot Hubl Jinja implementation that sets the query parameter of a url depending on the arguments, with toggle and fullPath
{#
Examples in order:
createQueryUrl('tags', 'online') // {url}?tags=online
createQueryUrl('tags', 'in-store', true) // {url}?tags=online,in-store
createQueryUrl('tags', 'omnichannel', true) // {url}?tags=online,in-store,omnichannel
createQueryUrl('tags', 'in-store', true) // {url}?tags=online,omnichannel
createQueryUrl('tags', null) // {url}
#}
{% macro createQueryUrl(key, value, toggleValue = false, fullPath = false) %}
{% set dictItems = request.queryDict.items() %}
{# collect all keys in the queryDict (queryDict.keys() doesn't work) #}
{% set keys = [] %}
{% for k, v in dictItems %}
{% do keys.append(k) %}
{% endfor %}
{% set hasKey = key in keys %}
{% set hasValue = value is string and value|length > 0 %}
{% set parts = [] %}
{% for k, v in dictItems %}
{% if k == key %}
{% if hasValue %}
{# toggle or set value #}
{% set values = v|split(',') %}
{% if toggleValue %}
{% if value in values %}
{# remove value from values array #}
{% set values = values|reject('in', [value]) %}
{% else %}
{# add value to values array #}
{% do values.append(value) %}
{% endif %}
{% else %}
{# overwrite the value instead #}
{% set values = [value] %}
{% endif %}
{% if values|length > 0 %}
{% do parts.append(k ~ '=' ~ values|join(',')) %}
{% endif %}
{# else don't append it to the parts #}
{% endif %}
{% else %}
{% do parts.append(k ~ '=' ~ v) %}
{% endif %}
{% endfor %}
{# if the key was not present in the queryDict we still want to add it #}
{% if not hasKey and hasValue %}
{% do parts.append(key ~ '=' ~ value) %}
{% endif %}
{% set basePath = fullPath ? request.fullUrl : request.path %}
{{basePath ~ '?' ~ parts|join('&')}}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment