Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Commit

Permalink
Improve ViewLocalizer resource look-up semantics:
Browse files Browse the repository at this point in the history
- Always prepend with application name and let underlying `IStringLocalizerFactory` do the name gymnastics
- Use ExecutingFilePath instead of view name
- Trim off the file extension (so your resource doesn't have to have ".cshtml" in its name)
- Improved doc comments
- #3718
  • Loading branch information
DamianEdwards committed Dec 18, 2015
1 parent 0c3e7b5 commit 87cd09b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/Microsoft.AspNet.Mvc.Localization/IViewLocalizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
namespace Microsoft.AspNet.Mvc.Localization
{
/// <summary>
/// A service that provides localized strings for views.
/// Represents a type that provides HTML-aware localization for views.
/// </summary>
public interface IViewLocalizer : IHtmlLocalizer
{
Expand Down
16 changes: 12 additions & 4 deletions src/Microsoft.AspNet.Mvc.Localization/ViewLocalizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Mvc.ViewFeatures.Internal;
using Microsoft.Extensions.Localization;
Expand All @@ -12,7 +13,8 @@
namespace Microsoft.AspNet.Mvc.Localization
{
/// <summary>
/// A <see cref="IHtmlLocalizer"/> implementation that provides localized strings for views.
/// An <see cref="IViewLocalizer"/> implementation that derives the resource location from the executing view's
/// file path.
/// </summary>
public class ViewLocalizer : IViewLocalizer, ICanHasViewContext
{
Expand Down Expand Up @@ -93,12 +95,18 @@ public void Contextualize(ViewContext viewContext)
throw new ArgumentNullException(nameof(viewContext));
}

var baseName = viewContext.View.Path.Replace('/', '.').Replace('\\', '.');
if (baseName.StartsWith(".", StringComparison.OrdinalIgnoreCase))
// Trim the file extension from the end of the path
var path = viewContext.ExecutingFilePath;
if (Path.HasExtension(path))
{
baseName = baseName.Substring(1);
var extension = Path.GetExtension(path);
path = path.Substring(0, path.Length - extension.Length);
}

var baseName = path.Replace('/', '.').Replace('\\', '.');
baseName = baseName.TrimStart('.');
baseName = _applicationName + "." + baseName;

_localizer = _localizerFactory.Create(baseName, _applicationName);
}
}
Expand Down

0 comments on commit 87cd09b

Please sign in to comment.