Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - Localization of d3.js (d3.locale example of usage)

I'm trying to use d3.locale() in my app to display Russian names of months. http://jsfiddle.net/j2feJ/2/ Also, I need shortMonths variable to be in English, because they are in English in my database.

var ru_RU = {
    "decimal": ",",
        "thousands": "xa0",
        "grouping": [3],
        "currency": ["", " руб."],
        "dateTime": "%A, %e %B %Y г. %X",
        "date": "%d.%m.%Y",
        "time": "%H:%M:%S",
        "periods": ["AM", "PM"],
        "days": ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"],
        "shortDays": ["вс", "пн", "вт", "ср", "чт", "пт", "сб"],
        "months": ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
        "shortMonths": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
}

But display is still in English. Am I using it wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling d3.locale() doesn't change the internal workings of d3, it just creates and returns a localization object. You need to capture this return value and store it in a variable so you can use it later. Given the object you created in your example code, you could do that like this:

var RU = d3.locale(ru_RU);

Then when you need a value to be localized, you must call for it explicitly. In your case, you want the full month names to be displayed as x-axis labels.

To do this, you can add a .tickFormat() to your x-axis, and specify that the format should be your localized version of a full month name.

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .ticks(5)
  .tickPadding(8)
  .tickFormat(RU.timeFormat("%B"));

locale.timeFormat() is equivalent to d3.time.format(), except that it uses the locale that you created instead of defaulting to en_US. In this case locale is the variable RU which we created earlier.

Here is the updated JSFiddle.

Remember, each time you want a localized string or value, you need to call for it explicitly. Use locale.numberFormat() in place of d3.format(), and locale.timeFormat() in place of d3.time.format(), where locale is a localization object created with d3.locale(). Hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...