Blazor HeadContent

Kuler Master 266 Reputation points
2024-06-03T17:10:50.0233333+00:00

I have some Open Graph meta tags that I add within the HeadContent. The problem is that I must add all those tags on every page.

<HeadContent>
    <meta name="description" content="@metaDescription" />
    <meta name="keywords" content="@metaKeywords" />
    <meta property="og:url" content="@currentUrl" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="@_localizer["PageTitle_Home"]" />
    <meta property="og:description" content="@_localizer["PageSubtitle_Home"]" />
    <meta property="og:image" content="@Path.Combine(_navigationManager.BaseUri,"img/og.png")" />

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:site" content="@test">
    <meta name="twitter:creator" content="@test">
    <meta name="twitter:title" content="@_localizer["PageTitle_Home"]">
    <meta name="twitter:description" content="@_localizer["PageSubtitle_Home"]">
    <meta name="twitter:image" content="@Path.Combine(_navigationManager.BaseUri,"img/og.png")">

</HeadContent>

Is it possible to have a component to be called and then only assign the different values as parameters?

Thank you

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,620 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,595 questions
{count} votes

Accepted answer
  1. Ping Ni-MSFT 4,720 Reputation points Microsoft Vendor
    2024-06-07T08:41:25.4933333+00:00

    Hi @Kuler Master,

    Here is a whole working demo for how to make a reusable component to display different meta data with targetframework .net 8 in Blazor:

    1.Custom Component named CustomMetaTag.razor

    @using Microsoft.Extensions.Localization
    @inject NavigationManager _navigationManager
    @inject IStringLocalizer<CustomMetaTag> _localizer
    <HeadContent>
        <meta name="description" content="@Description" />
        <meta name="keywords" content="@Keywords" />
        <meta property="og:url" content="@Url" />
        <meta property="og:type" content="website" />
        <meta property="og:title" content="@Title" />
        <meta property="og:description" content="@OgDescription" />
        <meta property="og:image" content="@Image" />
        <meta name="twitter:card" content="summary_large_image">
        <meta name="twitter:site" content="@TwitterSite">
        <meta name="twitter:creator" content="@TwitterCreator">
        <meta name="twitter:title" content="@Title">
        <meta name="twitter:description" content="@OgDescription">
        <meta name="twitter:image" content="@Image">
    </HeadContent>
    @code {
        [Parameter] public string Description { get; set; }
        [Parameter] public string Keywords { get; set; }
        [Parameter] public string Url { get; set; }
        [Parameter] public string Title { get; set; }
        [Parameter] public string OgDescription { get; set; }
        [Parameter] public string Image { get; set; }
        [Parameter] public string TwitterSite { get; set; } = "@crowd4cash";
        [Parameter] public string TwitterCreator { get; set; } = "@crowd4cash";
        protected override void OnParametersSet()
        {
            if (string.IsNullOrEmpty(Url))
            {
                Url = _navigationManager.Uri;
            }
            if (string.IsNullOrEmpty(Title))
            {
                Title = _localizer["PageTitle_Default"];
            }
            if (string.IsNullOrEmpty(OgDescription))
            {
                OgDescription = _localizer["PageSubtitle_Default"];
            }
        }
    }
    

    2.Use the component in Home.razor for example

    @page "/"
    
    @using Microsoft.Extensions.Localization
    @inject NavigationManager _navigationManager
    @inject IStringLocalizer<Home> _localizer
    <CustomMetaTag Description="Your page description here"
        Keywords="Your, Keywords, Here"
        Url="@_navigationManager.Uri"
        Title="@_localizer["PageTitle_Home"]"
        OgDescription="@_localizer["PageSubtitle_Home"]"
        Image="@Path.Combine(_navigationManager.BaseUri, "img/og.png")"
    />
    <h1>@_localizer["PageTitle_Home"]</h1>
    <p>@_localizer["PageSubtitle_Home"]</p>
    

    3.Add Localization Strings to Resource Files.

    4.Configure the localization in Blazor Server

    public class Program
       {
           public static void Main(string[] args)
           {
               var builder = WebApplication.CreateBuilder(args);
               // Add services to the container.
               builder.Services.AddRazorComponents()
                   .AddInteractiveServerComponents()
                   .AddInteractiveWebAssemblyComponents();
               builder.Services.AddHttpClient();
    
             //add this... 
               builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
               var app = builder.Build();
               // Configure the HTTP request pipeline.
               if (app.Environment.IsDevelopment())
               {
                   app.UseWebAssemblyDebugging();
               }
               else
               {
                   app.UseExceptionHandler("/Error");
                   // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                   app.UseHsts();
               }
               app.UseHttpsRedirection();
              
               //add this... app.UseRequestLocalization(app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);
               app.UseStaticFiles();
               app.UseAntiforgery();
               app.MapRazorComponents<App>()
                   .AddInteractiveServerRenderMode()
                   .AddInteractiveWebAssemblyRenderMode()
                   .AddAdditionalAssemblies(typeof(Counter).Assembly);
               app.Run();
           }
       }
    

    5.Configure the localization in Blazor WebAssembly

    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); //add this... 
    builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
    await builder.Build().RunAsync();
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Rena

    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,866 Reputation points
    2024-06-03T18:11:21.2533333+00:00

    if on every page, just move the code to app.razor.

    generally open graph data is fetched with a get (and will not load/execute javascript), so only static pre-render html will be seen.

    https://learn.microsoft.com/en-us/aspnet/core/blazor/components/prerender?view=aspnetcore-8.0


  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.