Rails How can I build a breadcrumb with different urls for each element?

Viewed 343

My controller contains:

@prefix = params[:asset_id]

where params[:asset_id] contains the subdirectory names like [downloads, company, brochure].

My view contains:

<ol class="breadcrumb">
  <li><%= link_to 'Start', admin_assets_path %></li>
  <% for item in @prefix.split("/") %>
    <li>&nbsp<%= link_to "/ #{item}", "" %></li>
  <% end %>
</ol>

The result would look like following:

Start / downloads / company / brochure

My Problem here of course is that all of the breadcrumbs will be linked to the same following url:

http://localhost:3000/int/en/admin/assets/downloads%2Fcompany%2Fbrochure%2F/path

I want all of them be linked to their respective URL, e.g.:

downloads: http://localhost:3000/int/en/admin/assets/downloads%2F/path

company: http://localhost:3000/int/en/admin/assets/downloads%2Fcompany%2F/path

brochure: http://../en/admin/assets/downloads%2Fcompany%2Fbrochure%2F/path

How should be the logic to get every breadcrumb its own url?

1 Answers

Firstly, let me note that you need to determine the logic of where you want to link to for each of the particular breadcrumb items.

As far as I can tell from your example, you are using the following convention to determine the link destination for a certain breadcrumb:

The link destination for the breadcrumb consists of:

  • a static path prefix (which in your case would be http://localhost:3000/int/en/admin/assets/),
  • the concatenation of all higher-or-same-level-breadcrumbs, joined by /. In case of item = 'company', that would be downloads/company,
  • and the static suffix /path.

In order to create these links you could use the following code:

<ol class="breadcrumb">
  <li><%= link_to 'Start', admin_assets_path %></li>
  <%
    items = @prefix.split("/")
    prefix = admin_assets_path
    suffix = '/path'
  %>
  <% items.each.with_index do |item, i| %>
    <%
      middle = items[0..i].join('/')
      path = prefix + middle + suffix
    %>
    <li>&nbsp<%= link_to "/ #{item}", path %></li>
  <% end %>
</ol>

However your actual question was:

How should be the logic to get every breadcrumb its own url?

Your current convention (breadcrumbs form links) has some limitations, for example internationalization is difficult and we cannot support cases where the logical breadcrumb structure does not mirror the url structure.

You might use something like a hash map or tree structure in order to model the actual site structure or have a look at gems made for this purpose, for example breadcrumbs_on_rails.

Related