feat: add $title and $description computed globals

pull/152/head
Matias Capeletto 5 years ago
parent 07e06257e9
commit 7c989fcc68

@ -55,6 +55,14 @@ Reference of [\$page](#page).frontmatter.
}
```
## \$title
Value of the `<title>` label used for the current page.
## \$description
The content value of the `<meta name= "description" content= "...">` for the current page.
## \$themeConfig
Refers to `$site.themeConfig`.

@ -92,6 +92,18 @@ export function createApp() {
return router.route.data.frontmatter
}
},
$title: {
get() {
return router.route.data.title || siteDataByRouteRef.value.title
}
},
$description: {
get() {
return (
router.route.data.description || siteDataByRouteRef.value.description
)
}
},
$themeConfig: {
get() {
return siteDataByRouteRef.value.themeConfig

@ -3,7 +3,7 @@ import matter from 'gray-matter'
import LRUCache from 'lru-cache'
import { createMarkdownRenderer, MarkdownOptions } from './markdown/markdown'
import { deeplyParseHeader } from './utils/parseHeader'
import { PageData } from '../../types/shared'
import { PageData, HeadConfig } from '../../types/shared'
const debug = require('debug')('vitepress:md')
const cache = new LRUCache<string, MarkdownCompileResult>({ max: 1024 })
@ -41,6 +41,7 @@ export function createMarkdownToVueRenderFn(
// inject page data
const pageData: PageData = {
title: inferTitle(frontmatter, content),
description: inferDescription(frontmatter),
frontmatter,
headers: data.headers,
relativePath: file.replace(/\\/g, '/'),
@ -101,3 +102,20 @@ const inferTitle = (frontmatter: any, content: string) => {
}
return ''
}
const inferDescription = (frontmatter: Record<string, any>) => {
return getHeadMetaContent(frontmatter.head, 'description') || ''
}
const getHeadMetaContent = (
head: HeadConfig[],
name: string
): string | undefined => {
if (!head || !head.length) {
return undefined
}
const meta = head.find(([tag, attrs = {}]) => {
return tag === 'meta' && attrs.name === name && attrs.content
})
return meta && meta[1].content
}

1
types/shared.d.ts vendored

@ -25,6 +25,7 @@ export type HeadConfig =
export interface PageData {
title: string
description: string
frontmatter: Record<string, any>
headers: Header[]
relativePath: string

Loading…
Cancel
Save