THp*_*ubs 3 javascript node.js ghost-blog
我正在使用Ghost平台运行博客.Ghost是建立在Nodejs上的,但我对此并不了解.我已经构建了以下代码,抓住每个帖子的第一张图片并将其设置为og:image.问题是它只在网站到达用户的机器后加载.是否可以从服务器执行此操作然后将其发送给用户?
$(document).ready(function() {
var siteURL = location.host;
if(
$('.post-template').length > 0 ||
$('.page-template').length > 0
) {
var featured_image = $('.post-content img[alt="featured-image"]').first().attr('src');
// check if the featured image exists
if(featured_image && featured_image.length > 0) {
var featured_image_fe = featured_image;
// create container for the image
if(featured_image_fe.substr(0,7) != 'http://'){
featured_image_fe = siteURL + featured_image_fe;
}
$('meta[property="og:image"]').attr('content', featured_image_fe);
} else {
var featured_image = $('.post-content img').first().attr('src');
if(featured_image && featured_image.length > 0) {
var featured_image_nfe = featured_image;
if((featured_image_nfe.substr(0,7) != 'http://') && (featured_image_nfe.substr(0,8) != 'https://')){
featured_image_nfe = 'http://' + siteURL + featured_image_nfe;
}
$('meta[property="og:image"]').attr('content', featured_image_nfe);
} else {
$('meta[property="og:image"]').attr('content', 'http://media.techhamlet.com/wp-content/uploads/2014/06/techhamlet.jpg');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
是的,这绝对是可能的.我已经找到了一个快速的黑客来获得og:图像支持在Ghost中工作.这绝对是一个非最佳解决方案,但它需要最少的代码更改.您需要安装cheerio并修改两个文件.
我们需要从第76行开始更新formatResponse函数.
var cheerio = require('cheerio');
function formatResponse(post) {
var $ = cheerio.load(post.html);
var firstImage = $('img').first();
if(firstImage) {
post.meta_image = firstImage.attr('src');
}
// Delete email from author for frontend output
// TODO: do this on API level if no context is available
if (post.author) {
delete post.author.email;
}
return {post: post};
}
Run Code Online (Sandbox Code Playgroud)
我们正在做什么通过cheerio运行发布HTML.抓取第一个图像,并将src填充到post对象的新变量(meta_image)中.这将使该变量可用于车把模板系统.
在这里我刚刚更新了这个{{! Page Meta }}部分:
{{! Page Meta }}
<title>{{meta_title}}</title>
<meta name="description" content="{{meta_description}}" />
{{#if this.post.meta_image}}
<meta property="og:image" content="{{this.post.meta_image}}" />
{{/if}}
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
Run Code Online (Sandbox Code Playgroud)
我们只是检查是否this.post.meta_image存在,以及它是否确实创建了元标记.
你应该真正做的是添加这个功能是为og:image的post对象添加一个额外的字段.然后你可以用管理员的单独字段填充它,或者你可以在保存帖子时解析html并将值放入适当的字段.这样,填充og:image的逻辑仅在保存页面时运行一次,而不是每次显示页面时.
| 归档时间: |
|
| 查看次数: |
374 次 |
| 最近记录: |