nixnixos

How to add values to a list at specific locations in Nix?


I would like to add certain strings to a list based on a conditional in Nix. For context, I am using this to conditionally have different Waybar modules.

At the moment, I have a solution, but I feel like there is probably a better way.

My current solution:

baseRightModules0 = [
    "group/expand"
    "wireplumber"
    "network"
    "privacy"
  ];

  baseRightModules1 = [
    "custom/wlogout"
  ];

  rightModules0 = components: 
    if components.bluetooth then baseRightModules0 ++ "bluetooth"
    else baseRightModules0;

  rightModules = components:
    if components.battery then (rightModules0 components) ++ "battery" ++ baseRightModules1
    else (rightModules0 components) ++ baseRightModules1;

Solution

  • Here's probably the most idiomatic Nix code for what you're asking. Noogle is your friend for finding library functions.

    {
      rightModules = [
        "group/expand"
        "wireplumber"
        "network"
        "privacy"
      ]
      ++ lib.optional components.bluetooth "bluetooth"
      ++ lib.optional components.battery "battery"
      ++ [
        "custom/wlogout"
      ];
    }