Skip to content

Commit

Permalink
Merge pull request #191 from frontity/add-dynamic-titles-to-mars
Browse files Browse the repository at this point in the history
feat(mars-theme): add dynamic <title> tags
  • Loading branch information
luisherranz committed Sep 4, 2019
2 parents c23ebf2 + e771ce4 commit d1de357
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/mars-theme/src/components/index.js
Expand Up @@ -5,6 +5,7 @@ import List from "./list";
import Post from "./post";
import Page404 from "./page404.js";
import Loading from "./loading";
import Title from "./title";

const globalStyles = css`
body {
Expand All @@ -25,10 +26,10 @@ const Theme = ({ state }) => {
return (
<>
<Head>
<title>{state.frontity.title}</title>
<meta name="description" content={state.frontity.description} />
<html lang="en" />
</Head>
<Title />
<Global styles={globalStyles} />
<HeadContainer>
<Header />
Expand Down
45 changes: 45 additions & 0 deletions packages/mars-theme/src/components/title.js
@@ -0,0 +1,45 @@
import React from "react";
import { Head, connect } from "frontity";

const Title = ({ state }) => {
// Get data about the current URL.
const data = state.source.get(state.router.link);
// Set the default title.
let title = state.frontity.title;

if (data.isTaxonomy) {
// Add titles to taxonomies, like "Category: Nature - Blog Name" or "Tag: Japan - Blog Name".
// 1. Get the taxonomy entity from the state to get its taxonomy term and name.
const { taxonomy, name } = state.source[data.taxonomy][data.id];
// 2. Uppercase first letter of the taxonomy term (from "category" to "Category").
const taxonomyCapitalized =
taxonomy.charAt(0).toUpperCase() + taxonomy.slice(1);
// 3. Render the proper title.
title = `${taxonomyCapitalized}: ${name} - ${state.frontity.title}`;
} else if (data.isAuthor) {
// Add titles to authors, like "Author: Jon Snow - Blog Name".
// 1. Get the author entity from the state to get its name.
const { name } = state.source.author[data.id];
// 2. Render the proper title.
title = `Author: ${name} - ${state.frontity.title}`;
} else if (data.isPostType) {
// Add titles to posts and pages, using the title and ending with the Blog Name.
// 1. Get the post entity from the state and get its title.
const postTitle = state.source[data.type][data.id].title.rendered;
// 2. Remove any HTML tags found in the title.
const cleanTitle = postTitle.replace(/<\/?[^>]+(>|$)/g, "");
// 3. Render the proper title.
title = `${cleanTitle} - ${state.frontity.title}`;
} else if (data.is404) {
// Add titles to 404's.
title = `404 Not Found - ${state.frontity.title}`;
}

return (
<Head>
<title>{title}</title>
</Head>
);
};

export default connect(Title);

0 comments on commit d1de357

Please sign in to comment.