Skip to content

Featured request: Auto-ID helper function #7734

@earthboundkid

Description

@earthboundkid

For some things, HTML requires unique-per-page ids. For example, a <label for="xxx"> and <input id="xxx"> pair. If you have a partial for a form, you need each form on the page to have unique IDs. Right now, I'm solving this with a .Scratch variable that just sets a counter per page. It works, but it's a little awkward because you have to pass .Page into a shortcode that needs an ID, and if you do it wrong you can accidentally reset the counter.

I propose a template helper function called autoid that returns a new ID every time you call it. It could take a prefix argument to make the IDs prettier for developers. Could work like this:

<!-- root file -->
<h1>Try our form!</h1>
{{ partial "form.html" . }}

<h2>No, please, try our form!</h2>
{{ partial "form.html" . }}

<!-- form.html -->
<label for="{{ $emailID := autoid "myform" }}">Email</label>
<input id="{{ $emailID }}" name="email">
<label for="{{ $nameID := autoid "myform" }}">Name</label>
<input id="{{ $nameID }}" name="name">

<!-- output -->
<h1>Try our form!</h1>
<label for="myform-0001">Email</label>
<input id="myform-0001" name="email">
<label for="myform-0002">Name</label>
<input id="myform-0002" name="name">

<h2>No, please, try our form!</h2>
<label for="myform-0003">Email</label>
<input id="myform-0003" name="email">
<label for="myform-0004">Name</label>
<input id="myform-0004" name="name">

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions