using System.Text.RegularExpressions; using Umbraco.Cms.Core.Composing; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Snippets { /// /// The collection of partial view snippets. /// public class PartialViewSnippetCollection : BuilderCollectionBase { public PartialViewSnippetCollection(Func> items) : base(items) { } /// /// Gets the partial view snippet names. /// /// The names of all partial view snippets. public IEnumerable GetNames() { var snippetNames = this.Select(x => Path.GetFileNameWithoutExtension(x.Name)).ToArray(); // Ensure the ones that are called 'Empty' are at the top var empty = snippetNames.Where(x => Path.GetFileName(x)?.InvariantStartsWith("Empty") ?? false) .OrderBy(x => x?.Length).ToArray(); return empty.Union(snippetNames.Except(empty)).WhereNotNull(); } /// /// Gets the content of a partial view snippet as a string. /// /// The name of the snippet. /// The content of the partial view. public string GetContentFromName(string snippetName) { if (snippetName.IsNullOrWhiteSpace()) { throw new ArgumentNullException(nameof(snippetName)); } string partialViewHeader = "@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage"; var snippet = this.Where(x => x.Name.Equals(snippetName + ".cshtml")).FirstOrDefault(); // Try and get the snippet path if (snippet is null) { throw new InvalidOperationException("Could not load snippet with name " + snippetName); } var snippetContent = CleanUpContents(snippet.Content); var content = $"{partialViewHeader}{Environment.NewLine}{snippetContent}"; return content; } private string CleanUpContents(string content) { // Strip the @inherits if it's there var headerMatch = new Regex("^@inherits\\s+?.*$", RegexOptions.Multiline); var newContent = headerMatch.Replace(content, string.Empty); return newContent .Replace("Model.Content.", "Model.") .Replace("(Model.Content)", "(Model)"); } } }