我正在使用 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');
}
}
}
}
最佳答案
是的,这绝对是可能的。我想出了一个快速的 hack 来获得 og:image 支持在 Ghost 中工作。这绝对不是最佳解决方案,但它需要最少的代码更改。您需要安装 cheerio 并修改两个文件。
核心/服务器/ Controller /frontend.js
我们需要从第 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};
}
我们正在做的是通过 cheerio 运行 post HTML。抓取第一个图像,并将 src 填充到 post 对象的新变量 (meta_image) 中。这将使该变量可用于 Handlebars 模板系统。
内容/主题//default.hbs
这里我刚刚更新了 {{! 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" />
我们只是检查 this.post.meta_image
是否存在,以及它是否创建元标记。
更“合适”的解决方案
要添加此功能,您真正应该做的是为 og:image 添加一个附加字段到 post 对象。然后您可以使用来自管理员的单独字段填充它,或者您可以在保存帖子时解析 html 并将值放入适当的字段中。这样,填充 og:image 的逻辑仅在保存页面时运行一次,而不是每次显示页面时运行。
关于javascript - 我们如何在将 javascript 代码发送给 nodejs 中的用户之前执行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25859092/