Link_to helper #303

Closed
BadMinus opened this Issue Mar 6, 2012 · 7 comments

8 participants

@BadMinus

There is a way to add class if page is current page?
Like that:
link_to "SomePage", somepage_path, :class => current_page

Now I only can hide or show link if it current or not by

link_to "SomePage", somepage_path, :if => :current

@tdreyno
Middleman member

Not built in, but you should have all the tools necessary to craft such a helper using request.path. Something like:

helpers do
  def magic_link_to(link, url, opts={})
    if request.path == link
      opts[:class] = "current"
    end
    link_to(link, url, opts)
  end
end
@tdreyno tdreyno closed this Mar 7, 2012
@samme

I think you want

if request.path == url

@kurtisnelson

The above code snippet doesn't work, even with == url.

 helpers do
    def nav_link_to(link, url, opts={})
      if "/" + request.path == url
        prefix = '<li class="active">'
      else
        prefix = '<li>'
      end
      prefix + link_to(link, url, opts) + "</li>"
    end
  end
@bhollis
Middleman member

Try this (not tested):

helpers do
    def nav_link_to(link, url, opts={})
      if current_resource.url == url_for(url)
        prefix = '<li class="active">'
      else
        prefix = '<li>'
      end
      prefix + link_to(link, url, opts) + "</li>"
    end
  end

(Requires Middleman 3.0.12)

@dallasbpeters

Did this work? What's the markup in the template to get this to roll?

@stephanos

FYI, I had to do this:

current_url = current_resource.url
if current_url == url_for(url) || current_url == url_for(url) + "/"

(maybe because I use the directory index?)

@scottelundgren scottelundgren added a commit to scottelundgren/codeforcharlotte.org that referenced this issue Jun 21, 2014
@scottelundgren scottelundgren Adds a helper function that extends padrino's link_to to check if the…
… current page URL matches the URL in the navigation and add the twitter active class

This was such an easy fix that as vexed me. I knew there had to be some way to do this but I hadn't really understand the right way within the middleman process to figure where to do this myself.
I go lucky and found middleman/middleman#303 (comment)
eb142cf
@joallard

Here's a lazy implementation I made on the fly:

  def current_page?(page)
    current = current_resource.url.gsub('/', ' ').strip
    target = page.gsub('/', ' ').strip

    current == target
  end

I'll try to propose the addition to the standard helpers in a PR when I get the time.

@scottelundgren scottelundgren referenced this issue in CodeForCharlotte/codeforcharlotte.org Mar 17, 2015
Closed

License? #99

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment