1

Has anyone implemented auto linking of words within a redactor field? For example, a rich text field would contain this:

A small boat surrounds a large ​island

In a channel there are entries titled boat and island. I would like to automatically link to these without the editor having to manually link them.

Not sure how approach this so any hints to get me on my way are most appreciated.

3

How about just using the replace filter?

{% set text = "A small boat surrounds a large ​island​​" %}

{% set linkedText = text|replace({'boat':'<a href="/whatever">boat</a>'}) %}

{{ linkedText|raw }}<br><br>

That works.

In theory there should be a way to do it with parseRefs too, but my initial test isn't working yet:

{% set refText = text|replace({'boat':'<a href="{entry:11102:}">boat</a>'}) %}

{% set parsedText = refText|parseRefs %}

{{ parsedText|raw }}

...which leaves an unparsed ref tag so far. I'm just heading out of the office but maybe a simple replace as above is enough to get you started?

|improve this answer|||||
1

Assuming you only need this to work on the front end of your site (i.e., you don't actually need to see the links inside the Redactor field in the control panel), something like this might do the trick:

{# Get the rich text content #}
{% set text = entry.richTextField %}

{# Get all entries that could possibly be linked #}
{% set entries = craft.entries.section('someSection').limit(null) %}

{# Loop through entries, replacing any words matching entry titles with a link #}
{% for entry in entries #}
    {% set text = text|replace({(entry.title|lower):'<a href="'~entry.url~'">'~entry.title|lower~'</a>'}) %}
{% endfor %}

{# Render the text #}
{{ text|raw }}

Note that there are several possible issues with the above:

  • You might see performance issues if you have a lot of entries to match (consider using the {% cache %} tag)
  • Lower/uppercase and capitalization issues are difficult to deal with (the above example only matches lowercase words and phrases to the entry titles)
  • Words and phrases with HTML tags inside won't match, i.e. "something something" wouldn't match the entry title "Something something"
  • Entries can have identical titles, so if you have more than one entry called "Something something" only the last one will be linked
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.