support adding description meta tag to pages

using the page context
This commit is contained in:
Peter Cai 2020-04-15 15:21:51 +08:00
parent 15f78ea632
commit e1033ff0b3
No known key found for this signature in database
GPG key ID: 71F5FB4E4F3FD54F
3 changed files with 18 additions and 6 deletions

View file

@ -67,7 +67,11 @@ struct PageContext {
// The pathname part of the URL
pathname: String,
// The current query string
query: String
query: String,
// Summary of the current page
// regardless of its type
// For use in <meta> tags
description: String
}
#[derive(Serialize)]
@ -148,11 +152,12 @@ fn build_handlebars() -> Handlebars<'static> {
return hbs;
}
fn build_page_context(url: &Url) -> PageContext {
fn build_page_context(url: &Url, description: String) -> PageContext {
PageContext {
base_url: url.origin(),
pathname: url.pathname(),
query: url.search()
query: url.search(),
description
}
}
@ -168,7 +173,7 @@ async fn _render_homepage(url: Url, tpl_name: &str) -> MyResult<String> {
.map_err(|_| Error::BadRequest("Failed to parse query string".into()))?;
let mut context = HomePageContext {
blog: &ROOT_CONTEXT,
page: build_page_context(&url),
page: build_page_context(&url, ROOT_CONTEXT.description.into()),
posts: vec![],
prev: None,
next: None
@ -225,7 +230,7 @@ pub async fn render_post(url: Url, post: blog::Post) -> MyResult<String> {
let post_cache = blog::PostContentCache::find_or_render(&post).await;
let context = PostContext {
blog: &ROOT_CONTEXT,
page: build_page_context(&url),
page: build_page_context(&url, strip_html_tags(&post_cache.summary)),
title: post.title,
url: post.url,
timestamp: post.timestamp,

View file

@ -171,4 +171,10 @@ fn default_maxage() -> u64 {
60 * 60 * 24 * 7 // default to a week
}
include!(concat!(env!("OUT_DIR"), "/build_timestamp.rs"));
include!(concat!(env!("OUT_DIR"), "/build_timestamp.rs"));
// Strip HTML tags from a string via JS binding
pub fn strip_html_tags(s: &str) -> String {
let js_str: JsString = s.into();
js_str.replace_by_pattern(&RegExp::new("(<([^>]+)>)", "ig"), "").into()
}

View file

@ -1,6 +1,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="{{ page.description }}">
<title>{{ #if title }}{{ title }} - {{ blog.title }}{{ else }}{{ blog.title }}{{ /if }}</title>
<link rel="stylesheet" href="/static/monokai-sublime.css?ver={{ build_num }}" />
<link rel="stylesheet" href="/static/style.css?ver={{ build_num }}" />