// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Razor;
namespace MvcSample.Web
{
///
/// A that replaces adds the language as an extension prefix to view names.
///
///
/// For the default case with no areas, views are generated with the following patterns (assuming controller is
/// "Home", action is "Index" and language is "en")
/// Views/Home/en/Action
/// Views/Home/Action
/// Views/Shared/en/Action
/// Views/Shared/Action
///
public class LanguageViewLocationExpander : IViewLocationExpander
{
private const string ValueKey = "language";
private readonly Func _valueFactory;
///
/// Initializes a new instance of .
///
/// A factory that provides tbe language to use for expansion.
public LanguageViewLocationExpander(Func valueFactory)
{
_valueFactory = valueFactory;
}
///
public void PopulateValues(ViewLocationExpanderContext context)
{
var value = _valueFactory(context.ActionContext);
if (!string.IsNullOrEmpty(value))
{
context.Values[ValueKey] = value;
}
}
///
public virtual IEnumerable ExpandViewLocations(ViewLocationExpanderContext context,
IEnumerable viewLocations)
{
string value;
if (context.Values.TryGetValue(ValueKey, out value))
{
return ExpandViewLocationsCore(viewLocations, value);
}
return viewLocations;
}
private IEnumerable ExpandViewLocationsCore(IEnumerable viewLocations,
string value)
{
foreach (var location in viewLocations)
{
yield return location.Replace("{0}", value + "/{0}");
yield return location;
}
}
}
}