šŸ“ 100% Templatable Lovelace Configurations

Iā€™m trying to have an SVG icon moving around over everything of the dashboard, (mimik a robot vacuum cleaning the house) with this JS code. The JS code wonā€™t seem to make it move, is there some limitation with HA or i made a mistake?

type: custom:config-template-card
entities: []
card:
  type: custom:html-template-card
  content: |
    <div id="vacuum">
      <img src="/local/appliances/robot_shark_anime_thickW.svg" width="50px" height="50px" />
    </div>
    <script>
      $(document).ready(function(){
          animateDiv();   
      });

      function makeNewPosition(){
          var h = $(window).height() - 50;
          var w = $(window).width() - 50;
          
          var nh = Math.floor(Math.random() * h);
          var nw = Math.floor(Math.random() * w);
          
          return [nh, nw];    
      }

      function animateDiv(){
          var newq = makeNewPosition();
          var oldq = $('#vacuum').offset();
          var speed = calcSpeed([oldq.top, oldq.left], newq);
          
          $('#vacuum').animate({ top: newq[0], left: newq[1] }, speed, function(){
            animateDiv();        
          });
      }

      function calcSpeed(prev, next) {
          var x = Math.abs(prev[1] - next[1]);
          var y = Math.abs(prev[0] - next[0]);
          
          var greatest = x > y ? x : y;
          var speedModifier = 0.1;

          var speed = Math.ceil(greatest / speedModifier);
          return speed;
      }
    </script>

Hey, Iā€™d like to use the dashboard-wide variables feature, which I understand is only in the master branch (not yet released). But HACS only gives me a spinning wheel forever, when I try to install the master branch. Is there a trick, I am missing?

Hi! I have a version with global vars. Will check it in HACS as soon as I am near PC (in a few days).

1 Like

Check this: Dashboard variables by swiergot Ā· Pull Request #109 Ā· iantrich/config-template-card Ā· GitHub
Here is a JS file with changes.

Thanks, that worked!

cd www/community/config-template-card/
wget https://github.com/iantrich/config-template-card/files/9503751/config-template-card.js.gz
gunzip -k config-template-card.js.gz

I wonder, if a new release might be appropriate with this featureā€¦

Hi, I canā€™t see an answer in this thread but it may have been covered beforeā€¦I want to show different cards depending on a variable state (if rain is coming, show the graph, otherwise show a markdown card that says no rain is coming)

I have the card working to show the graph and using a call to a variable it changes the title of the chart, but now I just want to be able to switch which card is used (or maybe change the style so the one I donā€™t want is hidden via CSS).

is that possible?

Current card, if its useful, is:

          - type: custom:config-template-card
            variables:
              getWeatherStatus: >
                var entity =
                states['sensor.openweather_all'].attributes.minutely;

                var data = [];

                var nextTime = 0;

                for (let i = 0; i < 59; i++) {
                  if (Object.values(entity[i])[1] > 0 ) {nextTime = 1000 * Object.values(entity[i])[0];break;}
                }

                console.log(Math.floor(((Date.now() - nextTime) / 1000)/60));

                var nextMessage = "No rain expected in the next hour";  
                if (nextTime > 0) {
                  if (Math.floor(((nextTime - Date.now()) / 1000)/60) <= 5) {
                    console.log("soon");
                    nextMessage = "šŸŒ§ļø is expected very soon";
                  } else {
                    console.log("later");
                    nextMessage = "Rain expected in " + Math.floor(((nextTime - Date.now()) / 1000)/60) + " minutes";
                  }
                }

                nextMessage;
            entities:
              - sensor.openmeteo_15min_data
              - sensor.openweather_all
            card:
              type: custom:apexcharts-card
              stacked: true
              header:
                show: true
                title: ${ getWeatherStatus }
              apex_config:
                yaxis:
                  show: false
                  max: 0.3
                chart:
                  height: 100px
                grid:
                  show: false
                legend:
                  show: false
              graph_span: 45min
              span:
                start: minute
              series:
                - entity: sensor.openweather_all
                  type: column
                  name: Rainfall
                  float_precision: 3
                  color: '#CC630F'
                  data_generator: |
                    var data = []
                    for (let i = 0; i < 59; i++) {
                      data.push([1000 * Object.values(entity.attributes.minutely[i])[0], Object.values(entity.attributes.minutely[i])[1]]);
                    }        
                    console.log("testing from here");
                    console.log(data);
                    return data;

Thanks
Chris

Possible ways:
ā€“ stock cards with ā€œvisibilityā€ feature
ā€“ custom state-switch card

I was wondering about state-switch, which I already use. It has a template option for state, which uses jinja statements to define the state which you can then set a switch on. But can I make a call to a config-template-card variable from within in a jinja template - I suppose it probably just needs to be a simple bit of jinja that literally returns what the variable is?

Also, whilst the state-switch card responds to state changes in real time, how would that work with the config-template variable embedded - does that variable actually get refreshed by config-template-card at any point?

Thx

Chris

  1. I would not recommend using CTC as a topmost card - i.e. ABOVE state-switch. Use CTC on the bottommost level.
  2. In many cases CTC may be not used at all. In your case you are using CTC only to get a dynamic title - and a very complex & resource-wasting card is placed inside CTC. Use a simple Markdown to show a dynamic title (& remove a gap between apexcharts & markdown by cardmod - see details in corr. threads) or compose a dynamic title by card-mod & ā€œ:afterā€ pseudoclass (ask details in card-mod thread).

You should avoid complexity since this is not a simple thing:

All fair points. I think that if I link state-switch card to the weather forecast entity then it will refresh as that is updated, and I could then just hide the graph if I always show the markdown above it with the title. I have made a template before that cycles through that forecast so I can just reuse that in the SS card template to return true (rain expected) or false (dry), with true being the CTC card plus chart, and false being blank

That might also mean the graph gets updated after every forecast refresh thanks to the SS link to the entityā€¦otherwise might have to do something nasty like having two graphs and changing the state of the SS card thus flip flopping between them. if SS doesnā€™t otherwise refresh the cards when the linked entity refreshesā€¦hope not!!

SS listens to the ā€œstatesā€ object & is supposed to switch cards immediately.
Updating the inner cards - a different issue: it is a job to be done by these cards themselves.
When a card is placed inside CTC - it is a different story: the inner card will be updated (full redraw in fact - which is not desirable for graph cards, stock gauge card, ā€¦) if some ā€œmonitoredā€ entity (i.e. declared in ā€œentitiesā€ option) is changed.

The forecast weather sensor attribute will change every couple of minutes, and for every change the graph will need to redraw as it shows the next hour of data, so I am ok with that.

Iā€™m starting to come back to CTC being the master here, as it will refresh when the entity updates, when SS might refresh. As the CTC will always be shown (as the markup card at least is always shown) this way I have one CTC and not two (one per SS state). Performance wise itā€™s for one dashboard and Iā€™ll take the hit I think (itā€™s not like Iā€™m rolling this out in a mass consumed platform)
Within I will do the always visible markup card and the chart that Iā€™ll hide. I guess I may as well do that then with a css visible settingā€¦
Not the most elegant but functionalā€¦.if it will work as planned!

Iā€™ll give this a try thank you

Still on this. I had it working with cardmod wrapped around the inner apexcharts within a CTC but its messy, and its not refreshing as I expected when the entity gets updated, so Iā€™m looping back to a problem I had earlier about style: in CTC configs not working as I expected

As I understand it the CTC config can have style: as a primary configuration sectionā€¦which, I expected, would make the card disappear if set to display: noneā€¦but it doesnā€™t (even with !important)

Should it? My intention is that it would be

style:
   display: ${ getCSS }

ā€¦where getCSS returns block (if its visible) or none (if hidden)

NB in the code below Iā€™m not even using the getCSS variable yet, Iā€™m just setting display to none explicitly to get that much working first.

For reference - full card code:

      - type: custom:config-template-card
        variables:
          getWeatherStatus: >
            var entity = states['sensor.openweather_all'].attributes.minutely;

            var data = [];

            var nextTime = 0;

            for (let i = 0; i < 59; i++) {
              if (Object.values(entity[i])[1] > 0 ) {nextTime = 1000 * Object.values(entity[i])[0];break;}
            }


            var nextMessage = "No rain expected in the next hour";   
            if (nextTime > 0) {
              switch (Math.floor(((nextTime - Date.now()) / 1000)/60)) {
                case 0:
                  var nextMessage = "No rain expected in the next hour";  
                case 1:
                case 2:
                  var nextMessage = "šŸŒ§ļø right now";  
                case 3:
                case 4:
                case 5:
                case 6:
                  var nextMessage = "šŸŒ§ļø is expected very soon";
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                case 12:
                case 13:
                case 14:
                case 15:                    
                  var nextMessage = "Rain expected in " + Math.floor(((nextTime - Date.now()) / 1000)/60) + " minutes"; 
                default:
                  var nextMessage = "Rain expected in about " + Math.round(Math.floor(((nextTime - Date.now()) / 1000)/60)/5)*5 + " minutes";
              }
            }

            nextMessage;
          getCSS: |
            var entity = states['sensor.openweather_all'].attributes.minutely;
            var data = [];
            var nextTime = 0;
            for (let i = 0; i < 59; i++) {
              if (Object.values(entity[i])[1] > 0 ) {nextTime = 1000 * Object.values(entity[i])[0];break;}
            }
            var output = "block";      
            if ( nextTime == 0 ) { 
              output = "none";
            }     
            output;        
        entities:
          - sensor.openweather_all
        style:
          display: none !important
        card:
          type: custom:apexcharts-card
          stacked: true
          header:
            show: true
            title: ${ getWeatherStatus }
          apex_config:
            yaxis:
              show: false
              max: 0.3
            chart:
              height: 100px
            grid:
              show: false
            legend:
              show: false
          graph_span: 45min
          span:
            start: minute
          series:
            - entity: sensor.openweather_all
              type: column
              name: Rainfall
              float_precision: 3
              color: '#CC630F'
              data_generator: |
                var data = []
                for (let i = 0; i < 59; i++) {
                  data.push([1000 * Object.values(entity.attributes.minutely[i])[0], Object.values(entity.attributes.minutely[i])[1]]);
                }        

                return data;
            - entity: sensor.openweather_all
              type: column
              name: Padding
              float_precision: 3
              color: '#202020'
              data_generator: |
                var data = [];
                var paddingVal = 0;
                for (let i = 0; i < 59; i++) {
                  paddingVal = 0.3-Object.values(entity.attributes.minutely[i])[1];
                  if (paddingVal < 0) {paddingVal = 0;}
                  data.push([1000 * Object.values(entity.attributes.minutely[i])[0], 0.3-Object.values(entity.attributes.minutely[i])[1]]);
                }        
                return data;

Edit: whilst I still want to understand this, I also just realised while reading through this thread for inspiration that you can embed card_mod inside the apexchart as a configuration item, so you dont have to wrap the apexchart in a card_mod card (and thus have a card within a card within a card!).
I need to see if this resolves the refresh issue, but it does solve the neatness issue. But I still prefer the style to be apples in the CTC if that is possible. However I know someone will mention that, so this preempts that

Actually @Ildar_Gabdullin I am finding that the CTC isnā€™t refreshing at all as entities update. I understand from our discussions baove that it ought to every time an entity listed under the entities config section is updated.

But the card isnt refreshing - but if i reload the page the updated chart shows so its CC not refreshing rather than the sensor not having data that seems to be the issue?

Have I misunderstood somewhere?

Cheers

ā€“Chris

Honestly I stopped following your case since you posted a long complex code.
There a simple rules:

  1. List ALL entities - which are used inside CTC - inside the ā€œentitiesā€ option. If some entity is not listed - then CTC will not be updated if this entity is changed.
  2. Use CTC only when it is really needed (not for card-mod, markdown, auto-entities, etc). Particularly for the ā€œCTC is used to create a titleā€ case - I already said, this is one of the worst practices; use a Markdown card with a jinja template for a title (just ā€œglueā€ Markdown card & a below card ā€œseamlesslyā€ by card-mod or a custom:stack-in-card to mimic a standard title).
  3. Use CTC only for the bottommost card/row/element - i.e. not for a stack (if not needed for some inner cards). not for a whole Entities card (if only a particular row is templated), not for a whole Picture-elements card (if only a particular elements is templated).

Also, I would not use CTC for apexcharts.
Why? Imho apexcharts is a very heavy card, it uses JS internally. And placing it inside CTC may cause ā€œissuesā€ā€¦

As for card-mod:

this is wrong.
Check examples for CTC here: main card-mod thread ā†’ 1st post ā†’ link at the bottom ā†’ CTC

Thanks for the reply.

Responding to those points:

  1. Re: the entities used, I think I have - I only use one entity (a sensor for weather) and that is listed. But that updates every minute and the CTC is not refreshing the card (chart) inside it

  2. I have two requirements CTC provides - a) dynamically (JavaScript/Jinja) output CSS style based on an entityā€™s data (using it for a title is just lazy of me), and b) refresh a chart every time an entity updates. I canā€™t find another card that can do either.

  3. I am using it bottommost. And for the reasons above I am using apexcharts in it (and it works perfectly). Iā€™d rather not be doing this, but I canā€™t find any other way of doing the two things described above!

Re card mod, thanks Iā€™ll read that link. I thought CTC had a style config of its own I didnā€™t realise I needed to use a card_mod.

Thanks

Chris

CTC is merely a ā€œwrapperā€.

Refreshing a chart is not a purpose of CTC - every chart card (stock, custom) is supposed to update the chart itself, no CTC is needed.
In your code you have 2 vars - ā€œgetWeatherStatusā€ (for a title - see my comment above, bad choice), ā€œgetCSSā€ (I do not see it is used anywhere; if for card-mod - it is NOT needed).

Thats there for one I make it work with the explicitly set display: none. It will be display: $( getCSS ) but since it doesnt work without the variable, I havent used the variable yet

With regard to the refresh I read the above that it would redraw the inner card if the monitored entity changed. That redraw is fine, performance hit is no problem as I specifically want it redrawn after every change (its a near-real-time graph of the next 60 minutes of rainfall, so it needs to keep redrawing every minute). Its for one screen Iā€™m using as a dashboard so I have loads of resources and no issue using them!

I have just put a console.log command in each of the variables declarations that writes to console every time its run in order to see when the CTC reevaluates the js code (in case its the ApexChart not redrawing properly) and its not outputting anything until I manually refresh the dashboard page in the browser