Importing an external JS lib to use in custom:button-card

Sorry - I can’t see what I’m doing wrong here, having tried a few ways…

Trying to import and use GitHub - SheetJS/printj: sprintf for JS to give me an sprintf() I can use to format stuff in custom:button-card.

I downloaded the printj.js, installed in /config/www/js/printj.js and added /local/js/printj.js as a Lovelace JS module in the config UI. The browser can see my-ha.mydomain:8123:/local/js/printj.js just fine - but trying to make use of it:

      [[[
          return PRINTJ.sprintf("%s", "Wibble");
      ]]]

throws an error in the browser (not an HA error, rest of the cards are fine - this is an error in the console in Chrome’s Dev Window).

I’m clearly not including the module correctly - does anyone see anything obviously wrong?

I’ve just had a lot of success including local and Google fonts via the Lovelave resource UI, just stuck on the JS side…

Many many thanks in advance :+1:

OK - solved it. Something funny about that library. I switched to:

downloaded to /config/www/js/sprintf.js

Configured Lovelace to add the JS Module resource: /local/js/sprintf.js

Then, in custom:button-card config, I used code like:

  custom_fields:
    temperature1: |
      [[[
        if (variables.temperature1 in states)
        {
          var t = states[variables.temperature1].state;
          if (t == "unavailable")
          {
            return "N/A";
          }
          t = parseInt(t);
          t = Math.floor(t*10 + 0.5)/10;                 
          return sprintf("%0.1f°C", t);
        }
        return "N/A";
      ]]]

and it works a treat!

I highly recommend adding some sort of sprintf library - it makes things so much easier and it’s pretty poor JS doesn’t have it as a core function. I mean it’s only been in C since about 1973 and the idea of printf goes back to 1966 before I was born, in BCPL’s writef function.

Still… :joy::joy::joy:

1 Like