I'm making a website, but I'd like it to automatically pair words with links. How would I do this?

Question:
On my site, I’d like it to automatically pair words with links. How would I do this?

Repl link:
WorldCache - Home
WorldCache on Replit

Example:
If I type “WorldCache” anywhere on my site, across all of the HTML pages, I’d like the site to automatically link the text to the home page of WorldCache without me ever having to manually input an ‘a’ tag.

I think you could do this with some JavaScript, I’ll look through some of my Repls in a bit because I think I’ve done something similar before.

3 Likes

Report back if you have any ideas!

1 Like

The preferable way to do something like this would be to modify your content before it reaches your customer rather than using JavaScript on the client. For example, some customers may disable JavaScript.

Flask uses Jinja as it’s templating language - I bet you could use replace()and some of the other features of Jinja to achieve this on the server. If the content is static, pre-processing the html files before publishing would also make sense.

2 Likes

I went ahead and made a repl showing how you can use replacing to achieve link substitution with jinja filters. I’ve covered some of the drawbacks (chaining implications) and safety considerations. Let me know what you think:

https://replit.com/@samatreplit/Jinja-word-replacement

3 Likes

That’s a good point actually.

But if you’re only using frontend @RedCoder, and you want some simple JavaScript, make a <script> tag and put this as its contents:

document.addEventListener("DOMContentLoaded", () => {
  // page contents has loaded
  document.body.innerHTML=document.body.innerHTML.replaceAll("WorldCache", '<a href="https://worldcache.redcoder.repl.co">WorldCache</a>')
})

This is a really bare-bones solution that doesn’t handle things such as, if you already had a tag that said WorldCache, or even just a big text element like this one saying it:
image

If you need me to write a more in-depth solution with the checking and stuff, I can.

And by the way as Sam said once again:

If this functionality is 100% necessary (if they have JS disabled, it just won’t do the links.), then you can make a <noscript> tag that you can make redirect to a JavaScript Disabled page. But there’s not a lot of people who disable their JS (especially since it’s crucial for many websites’ functionality), so you probably won’t need this and it would be fine to just have them not link

3 Likes

So this would link the set word(s) to a link?

1 Like

Yes. And if you want to add more words to replace with HTML, you can just put another .replaceAll call directly after the first one.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.