Navigation menu featuring unique links for varying pages

This application is built on Ruby on Rails, using Ruby version 2.1.4 and Rails version 4.1.14.

I have a Javascript dropdown menu in the header bar that displays a list of items. However, I'm struggling to figure out how to dynamically change the menu options based on the current page.

For example, the "Item view" page may display a certain set of options, while the "Item Edit" page has a different set of options. The challenge is to have the menu items change dynamically on each page.

The header bar, including the dropdown menu, is a partial that is included in every page before the main content. The menu options themselves need to be dynamic.

My initial approach was to define an array (@menulinks) on each page, specifying the menu items and their respective URLs. For example:

@menulinks = {'Edit' => '/item/edit/', 'Delete' => '/item/delete/' etc etc}

I then intended to pass this array into the UL element that controls the menu in the header bar partial. However, I realized that the links require additional logic, such as calling methods using link_to. For instance, a delete link might look like this:

= link_to "Delete", item_path(@item), method: :delete, data: {confirm: "Are you sure you want to delete this item?"}

My question now is how to properly pass such complex links into the UL element. Is there a way to escape the link part so that Rails can interpret it correctly within the UL?

Alternatively, I wonder if I am overcomplicating the situation and if there is a simpler solution to achieve the dynamic menu options.

Answer №1

If you're looking to customize the menu links in your application, using a `before_filter` and helper methods could be a good approach. You can set up a default menu in your `ApplicationController` and override it in other controllers as needed:

class ApplicationController < ActionController::Base

  before_filter :setup_menu_links

  protected

  def setup_menu_links
    @menu_link_list = :default_menu_links
  end

end

class OtherController < ApplicationController

  protected

  def setup_menu_links
    @menu_link_list = :other_menu_links
  end
end

Define your menu links in helper classes:

class ApplicationHelper
  def default_menu_links
    [
      link_to('First item', ...),
      link_to('Second item', ...)
    ]
  end
end

class OtherHelper
  def other_menu_links
    [
      link_to('Other first', ...),
      link_to('Other second', ...)
    ]
  end

Then, call the appropriate method in your menu partial using `send`:

%ul.dropdown-menu
  - self.send(@menu_link_list).each do |menu_link|
  %li= menu_link

Feel free to adapt and expand upon this idea to suit your specific needs.

Answer №2

I realized I was over-complicating things. Here's one approach (though maybe not the most efficient, any other suggestions?):

First, in the partials for each page, create a local variable for each link:

    del_link = link_to "Delete", item_path(@item), method: :delete, data: {confirm: "Are you sure?"}
    edit_link = link_to "Edit", edit_dashboard_path(@dashboard)

Then, gather these links into an array:

    @menuitems = [del_link, edit_link]

Next, in the haml header with the menu, iterate through the array to display the links in a UL:

    %ul.dropdown-menu
      - @leftmenuitems.each do |link|
        %li= link_to link

It appears to be functioning as expected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically allocate a controller to an element following the Bootstrap process

I have a unique AngularJS application that is initialized manually at a specific time. Later on, I need to display an HTML element without any ng-controller assigned to it. Is there a way to dynamically add an ng-controller to this element in order for it ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

AngularJS text markers

In order to streamline the process of managing tags with random content, I have devised a 'tag' manipulation system using the angular-ui alert mechanism. The system includes a factory and a directive as follows: Factory: app.factory( &a ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

How can I troubleshoot jQuery not functioning in iOS even though it works on Safari?

Trying to implement jQuery on a website using xCode simulator for testing, but experiencing issues. Works fine on Safari webkit though. Click here to view the site. I would appreciate finding out what's causing the problem, as well as advice on how t ...

Is it possible for two-way binding to function in index.html within Angular 4?

Does two-way binding function in index.html? I have some links and metadata in index.html. How can we define head parameters in a component? <head> <meta name="og:title" content={{titleValue}}> <meta name="og:url" content={{urlValue}}> & ...

JavaScript loop to target a specific item

My goal is to animate the correct div under each navigation item, rather than all of them with the "navItemUnder" class. You can see exactly what I mean by hovering over a navigation item in this codePen. I am looking for a solution to target only one lin ...

Challenges when working with AJAX/jQuery in terms of fetching JSON data and setting dataType

I am currently facing a challenge with my practice of AJAX/jQuery coding. Despite my efforts to learn and improve, I find the concepts of jQuery and AJAX quite perplexing. Specifically, I am struggling to understand dataTypes and how to manage different ty ...

Setting a bookmark feature in HTML using localStorage: A step-by-step guide

I'm working on a simple code that captures the text content of a dynamically updated <h1> element and stores it as a "bookmark" in localStorage. I want to enable users to save or delete the bookmark by clicking a button. Below is a basic version ...

Cloning a checkbox using Jquery

I am working on a search page that utilizes checkboxes to display results. After the user selects certain options and triggers a reload of the page, I want to provide an easy way for them to remove their selections by displaying them at the top of the page ...

Is it possible for the r.js optimizer to generate a fresh index.html file that links to the compiled files

After using r.js to optimize my project, I'm wondering how to generate a single index.html file that includes just one optimized script and one CSS file. Would I need to manually write this post-build or is there another way to achieve this? ...

The vacant array suddenly fills up with content once it is accessed

I encountered a strange scenario where the console.log indicated that the array was empty. However, upon inspection, I found 2 elements within it. This unexpected behavior prevented the component from rendering as it believed that conversations was empty. ...

AngularJS checkbox validation requires a minimum of two checkboxes to be selected

When using AngularJS, I am looking to create a validation rule where a minimum of 2 checkboxes must be checked for the input to be considered valid. Here is what I have attempted: <div ng-repeat="item in items"> <label><input type="chec ...

Script for converting Fixed Positioned Elements to Static

I am frequently finding that elements on web pages are causing disruptions due to their fixed positioning. I am exploring ways to disable the position: fixed CSS rules on any website I visit. To address this issue, I have developed a userscript specifical ...

The value of the variable remains consistent throughout the .each function when using JQuery's .post() method

I am facing a dilemma with a variable value discrepancy within the $.post function compared to the parent function $(element).each(function. Below is the snippet of my code: $(document).ready(function() { $(".list").each(function() { var a = $(thi ...

Making Cross-Origin Requests using jQuery's Ajax function and PHP

I've attempted numerous times to make this function properly, but for some reason, I just can't seem to figure it out. Initially, everything was working flawlessly for a few requests, and then out of the blue, it stopped functioning. Below is t ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Deduct a digit from a variable

My goal is to decrease the value of revlength each time the loop runs. For example, if there are 2 posts by 'A Google user', then subtract 2 from revlength. This is my attempted solution: var revlength = place.reviews.length; if (place.reviews[ ...

Ways to assign scores to every response button

Below is an excerpt of code that showcases a list of potential answers for each question in the form of checkbox buttons. The task at hand is to assign marks to each answer button, which can be retrieved from the database. Marks for correct answers are obt ...

The Node-Slack Web API feature chat.delete consistently returns a "channel_not_found" error for any channel, despite the fact that the

I've been experimenting with creating a basic chat bot using the slack-node web API and botkit. However, I've encountered an issue while trying to utilize the chat.delete feature. Despite successfully listing all channels along with their IDs and ...