Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thibaut-decherit/57bc28f50c244d361e6fcf75f25bcafa to your computer and use it in GitHub Desktop.
Save thibaut-decherit/57bc28f50c244d361e6fcf75f25bcafa to your computer and use it in GitHub Desktop.
Symfony - Head and Page Title Generation

Symfony - Head and Page Title Generation

app/config/config.yml:

parameters:
  website_name: Website name here
twig:
  globals:
    website_name: '%website_name%'

See http://opengraphprotocol.org/ about Open Graph, https://davidwalsh.name/twitter-cards about Twitter cards and https://css-tricks.com/essential-meta-tags-social-media/ about social media meta tags in general.

app/Resources/views/base.html.twig:

<html lang="{{ 'head.language_code' | trans }}">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
        <meta name="description" content="{{ 'head.description' | trans }}"/>
        <meta property="og:locale" content="{{ 'head.language_code' | trans }}"/>
        <meta property="og:site_name" content="{{ website_name }}"/>
        <meta property="og:title" content="{{ page_title is defined ? page_title : website_name }}"/>
        <meta property="og:type" content="website"/> {# Probably website #}
        <meta property="og:description" content="{{ 'head.description' | trans }}"> {# Max 70 characters (Twitter guidelines) #}
        <meta property="og:url" content="{{ app.request.uri }}"/>
        <meta property="og:image" content="put-image-path-here"/>
        <meta name="author" content="put-author-name-here">
        <title>{{ page_title is defined ? page_title ~ " | " }}{{ website_name }}</title> {# Could be another separator than |, e.g. - #}
        {% block stylesheets %}
            <link href="{{ asset('build/global.css') }}" rel="stylesheet" type="text/css"/>
        {% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}"/>
    </head>
</html>

app/Resources/translations/messages.en.yml

#Head

head:
  description: Website description here
  language_code: en-US


#Page titles

page_title:
  your_page: Page title here

your-page.html.twig:

{% extends 'base.html.twig' %}

{% set page_title = 'page_title.your_page' | trans %}

{# Content of your page here. #}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment