Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate controller action_name in Rails 4

I want to translate my applications' views and as I'm using partial to render headers for each view like this:

<%=t "#{controller.controller_name.capitalize} #{controller.action_name}" %>

...I got stucked on translating them. How do I translate controller.action_name in custom translation file?

I've tried to access action names like this:

  parkings:
    index: "Parkings index"
    new: "New %{model}"

And many different variations of it, but every one failed. Could you help me?

This is a fragment of my controller:

  def new
    @parking = Parking.new
  end

  def create
    @parking = Parking.new(parking_params)

    if @parking.save
      redirect_to @parking, notice: t(:parking_created)
    else
      render action: 'new'
    end
  end

Thanks.

like image 244
ZuzannaSt Avatar asked Nov 25 '14 11:11

ZuzannaSt


2 Answers

You should have the translations in your locale file. Add an underscore or hyphen to separate words in the key

eg:

# config/locales/en.yml
en:
  parkings_index: Parkings index
  parkings_new: Parkings new page

view file

<%=t "#{controller_name}_#{action_name}" %>
like image 170
Santhosh Avatar answered Oct 07 '22 07:10

Santhosh


First of all, when you say #{controller.controller_name} it means that you have an object called controller accessible from your view, which is not true. Even if you manage to access the controller and the name of its action I don't think it's worth the effort and time.

Instead, you can structure your translation file somehow like this:

views:
  model_name (parkings): "Parkings"
    action_1_name (index): "Parkings Index"
    action_2_name (new): "New Parking"
    ...

and in your view say (for example) <%= link_to (t "views.model_name.action_name"), :action %>

like image 36
sebkkom Avatar answered Oct 07 '22 06:10

sebkkom