Adding fragment id to URL in controller

Is there a way to add a fragment identifier (an element id after a “#”) to a url in a controller? I’ve tried changing the request_path in the conn object but have had no luck.

@kohlerjp can you please provide more information on what you are trying to achieve? Do you want to redirect somewhere with a fragment? Do you want to generate a link with a fragment? Thank you.

Hello @josevalim,

Sure, I’m trying to link to a specific HTML element on a template that is rendered through a controller. I’m hoping to achieve the same effect of a URL of the form “/pages?val=true#section-heading”

So If I was in the page controller, I’d like to do something similar to:

    def index(conn, params) do
      conn
      |> append_fragment(params)
      |> render("index.html")
    end

What fragment shall that function append? You do not specify one… Also I can’t really see where it should append it to…

If you want to actually do something with the fragment then I have to admit that your server doesn’t usually know about if it was set or not, since it is not transferred from the client to the server, but is only known to the client.

Do you want to redirect or do you want to render your index.html and have one particular element use a fragment in its link?

I’m trying to have the controller render index.html, but essentially “scroll” to the specific HTML element. Similar to the anchor method in Rails. I guess I could just construct the new URL and use a redirect, but I was curious if there was a different way.

Hi Kohlerjp,

I could use # for navigation like this:

  1. I know the fragment identifier in my view and use a link like this to navigate:

    <%= for i <- @searchEmpresas do %>

    <%=raw i.name%>

    <%end%>

Then, in my controller I can extract and pass the fragment identifier:

def index(conn, params) do
    case params do
      %{"scrollTo" => scrollTo} ->
        scrollTo = scrollTo
        render(conn, "index.html", scrollTo: scrollTo)
      _ ->
        scrollTo = nil
        render(conn, "index.html", scrollTo: scrollTo)
    end  
  end

If you only know the fragment identifier in your controller and not in your view, just do this:

def index(conn, _params) do
     scrollTo = "myFragmentId"
     render(conn, "index.html", scrollTo: scrollTo)
 end

Finally I use in my “index.html”:

<script>
    location.hash = "<%=@scrollTo%>"
</script>

This is a simplification that I think could help you.

3 Likes