Best approach to add "if" css and script links in default instead of custom-{name}

Hello
I would like to include the Bootstrap css libraries, but only for one post type (as the libraries and frameworks are large) that I want to use if for. I am able to make a custom-{name}.hbs for my custom post. And the css and scripts do link this way.

The issue is, when I add the link in at the custom post level (instead of the default.hbs) it breaks all the other CSS going on in the theme for the site. It would also be an EXTENSIVE rework to make bootstrap play nice here. But when I add it in the head, it would be very manageable and would let me do some of the things I want to use bootstrap for.

The custom post type is being realized with a tag. But when i use {if}, {has} or {is} helpers to try and recognize the tag for a post, in the default.hbs it simply ignores the link/doesn’t find the tag.

What is the best approach to recognize the tag at the default level??

And here is an sample of what I have tried:

    <head>
        <title>{{meta_title}}</title>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="HandheldFriendly" content="True" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        {{#has tag="data"}}

            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

        {{/has}}

        <link rel="stylesheet" type="text/css" href="{{asset "css/global.css"}}" />
        <link rel="stylesheet" type="text/css" href="{{asset "css/notifications.css"}}" />

        <script src="{{asset "js/global.js"}}"></script>
        <script src="{{asset "js/custom-elements.js"}}"></script>

I think your problem is that you aren’t in the post context when you’re checking for the tag. So, in default.hbs, you’ll need to wrap the #has block with {{#post}} and {{/post}}. Ohhh, and I’m thinking you’d better check whether it’s a post, first. So…

{{#is "post"}}
{{#post}}
        {{#has tag="data"}}

            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

{{else}} 
{{!-- do you need to load anything here? --}} 
        {{/has}}
{{/post}}
{{/is}}

Bonus hint, in case you need it: #has matches the tag name, not slug. That always trips me up.

1 Like

Oh. Thank you. That was the issue! Still new to ghost. I appreciate the help.

1 Like