GravCMS field unique ID

700 views Asked by At

I'm building a modular template for an accordion menu in GravCMS.

I need a generated unique identifier for for the id's; Is there anything pre-existing that I can call and use for the identifier? If not, do I need to create an extra field and generate it when saved?

Currently where I have {{ pane.pane_title }} in my twig is where I'll be needing a unique ID.

Any advice on practice here is much appreciated.

My accordion.yaml file looks like this:

title: Accordion
@extends: default

form:
  fields:
    tabs:
      type: tabs
      active: 1

  fields:
    panes:
      type: tab
      title: Accordion Panes
      fields:
        header.panes:
          name: panes
          type: list
          label: Panes

          fields:
            .pane_title:
              type: text
              label: Title
            .pane_content:
              type: editor
              label: Content

My file, accordion.html.twig looks like this:

<div class="container">
<div class="row">
    <div class="panel-group" id="accordion">
        {% for pane in page.header.panes %}
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#collapse-{{ pane.pane_title }}">
                            {{ pane.pane_title }}</a>
                    </h4>
                </div>
                <div id="collapse-{{ pane.pane_title }}" class="panel-collapse collapse">
                    <div class="panel-body">{{ pane.pane_content }}</div>
                </div>
            </div>
        {% endfor %}
    </div>
</div>

1

There are 1 answers

0
zzzzBov On BEST ANSWER

Assuming pane has a unique slug you'd be better off using the slug than pane_title, as it seems likely that you could end up with special characters that would otherwise require escaping.

If slug isn't available, you can generate random unique strings for IDs:

{% for pane in page.header.panes %}
  {% set guid = random_string(36) %}
  ...
  <div id="collapse-{{guid}}"...>
  ...
{% endfor %}

However if you need to make sure that the IDs remain consistent across page views (such as for linking directly to specific panels), you're probably going to want to MD5 hash the title which removes the need to escape any characters:

{% for pane in page.header.panes %}
  {% set guid = pane.pane_title|md5 %}
  ...
  <div id="collapse-{{guid}}"...>
  ...
{% endfor %}