dipth

dipth

Autolinking urls in string (replacing urls with link tags)

I’m having a bit of trouble wrapping my head around how to implement an autolinking feature in my Phoenix application. Something like rails_autolink from rails (GitHub - tenderlove/rails_autolink: The auto_link function from Rails · GitHub)

The idea is that I want to scan some user-content and replace all urls with link-tags.

Now, I could technically just make a regular expression and just use it with String.replace to replace the urls, but since I will be using this in combination with text_to_html to also split the text into paragraphs it becomes a little more complex, since text_to_html returns a {:safe, string} tuple. Furthermore when I start replacing the urls by using the Phoenix.HTML.Link.link it becomes a bit of a mess, since I end up with something like:

["<p>This is a test:\r<br>\n", {:safe, [60, "a", [[32, "class", 61, 34, "embed", 34], [32, "href", 61, 34, "https://www.youtube.com/watch?v=CmAI_MwdASw", 34]], 62, "https://www.youtube.com/watch?v=CmAI_MwdASw", 60, 47, "a", 62]} | "</p>\n"]

Which Phoenix seems to choke on:

ArgumentError at GET /forums/4/forum_topics/16
argument error
nofile
No code available.
:erlang.iolist_to_binary/1
Called with 1 arguments
["<p>This is a test:\r<br>\n", {:safe, [60, "a", [[32, "class", 61, 34, "embed", 34], [32, "href", 61, 34, "https://www.youtube.com/watch?v=CmAI_MwdASw", 34]], 62, "https://www.youtube.com/watch?v=CmAI_MwdASw", 60, 47, "a", 62]} | "</p>\n"]

I think I’m missing something here. What would be the “correct” way to accomplish this?

Most Liked

alexparker

alexparker

I’m working on this as well, if I figure it out and remember to come back, I’ll add my solution here. Or if you figured it out, do update please.

voughtdq

voughtdq

Have you tried using Phoenix.HTML.safe_to_string/1 on the result of text_to_html?

MKoussa

MKoussa

For anyone who arrives here, this is what I found to work. Not perfect, but a starting point.

  # only accepts https
  @url_regex ~r/(https:\/\/[^\s<]+)/i

  def linkify(text) when is_binary(text) do
    text
    # Escape ALL user content
    |> html_escape()
    # Get the escaped HTML string
    |> safe_to_string()
    # Inject safe <a> tags
    |> replace_urls()
    # Mark final output as safe
    |> raw()
  end

  defp replace_urls(escaped_html) do
    Regex.replace(@url_regex, escaped_html, fn url ->
      ~s(<a href="#{url}" target="_blank" rel="noopener noreferrer">#{url}</a>)
    end)
  end

And then in your HEEX:

<%= linkify(@content_to_linkify) %>

If anyone knows of a better way, I am open to improvements and suggestions!

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement