问题
All my Blogger posts have Labels, but I choose not to show them on my Blogger Site. On my Blogger Dashboard -> Posts, I still can see all my labels for each post and filter them by label, which is what I want. But when I try to check if the current post has a specific label (which it does have), the following code doesn't work (right before </body>
):
<b:section id="testSection" name="Test Section">
<b:if cond='data:posts any (p => p.labels any (l => l.name == "Label1"))'>
<script type="text/javascript">
console.log("Label1");
</script>
<link href='post-style-for-label1.css' rel='stylesheet' type='text/css'/>
</b:if>
</b:section>
I read the answer here, saying that we can't check data:post.labels
outside Blog widget, but when I placed it inside a widget, it says widget cannot contain <b:if>
-- this is why I placed it under <b:section>
. But at the end, I still can't make my code to detect Label1. I tried the following code but not working too:
<b:if cond='data:post.labels any (label => label.name == "Label1")'>
<script type="text/javascript">
console.log("Label1");
</script>
<link href='post-style-for-label1.css' rel='stylesheet' type='text/css'/>
</b:if>
If I can remember correctly, I have removed the code that displays the labels, but is it necessary to display the labels on the site in order for the code to work? I doubt that because Blogger does have all my labels for every post. How can I make my code to work? Thanks in advance.
回答1:
Blogger theme provides several types of widgets like Header, Blog, profile...(26 type) and each type has its data tags. In your example, data:post.labels
belongs to the widget type Blog so, you cannot use it outside widget tags.
Also, a widget can only contain b:includeable
tags (similar to functions in Javascript)
If your theme already has a blog widget, place your code in the tag b:includable
with id='main'
otherwise, create one like the following:
<b:widget id='Blog1' type='Blog'>
<b:includable id='main'>
<b:loop values='data:posts' var='post'>
<b:if cond='data:post.labels any (label => label.name == "Label1")'>
<script type="text/javascript">
console.log("Label1");
</script>
</b:if>
</b:loop>
</b:includable>
</b:widget>
来源:https://stackoverflow.com/questions/60607197/how-to-check-if-a-blogger-post-has-specific-label-when-the-label-is-hidden