custom-cards / button-card

❇️ Lovelace button-card for home assistant
MIT License
1.97k stars 242 forks source link

Documentation update - variables with JavaScript code is okay #626

Open kpoppel opened 2 years ago

kpoppel commented 2 years ago

Is your feature request related to a problem? Please describe. Not a problem, a feature related to variables which happens to work.

Describe the solution you'd like Improvement of the documentation here: https://github.com/custom-cards/button-card#variables

Describe alternatives you've considered N/A

Additional context As an extra feature with variables they can be used with arbitrary JavaScript code as well. I had some code I had to repeat both for state and style purposes, and thought it could be nice if I could define a block of reusable code. So why not try a variable.

Example (essentials only):

my_card_template:
  variables:
    # Use variables to hold Javascript code - now it can be reused!
    my_function: >
      [[[
        // Can do anything here
        return [1, 2, 3];
      ]]]
  styles:
    card:
      - background: >
          [[[
            const data = variables.my_function;
            if(entity.state <= data[0]) {
              return "linear-gradient(90deg, rgba(162,255,162,1) 0%, rgba(90,209,52,1) 47%, rgba(0,255,59,1) 100%)"
            } else if(entity.state <= data[1]) {
              return "linear-gradient(90deg, rgba(139,136,41,1) 0%, rgba(201,212,19,1) 47%, rgba(241,255,0,1) 100%)"
            } else {
              return "linear-gradient(90deg, rgba(107,13,13,1) 0%, rgba(201,21,25,1) 47%, rgba(255,0,0,1) 100%)"
            }
          ]]]
  label: >
    [[[
      const data = variables.my_function;
      return "Data use 1:"+data[0];
    ]]]
  name: >
    [[[
      const data = variables.my_function;
      return "Data use 1:"+data[1];
    ]]]