how to change value dynamically variable

2019-08-08 03:49发布

how to use dynamically dotless variables. I mean how to assign value dynamically in dotless file. Is there any way?

style.less file contain

@url_image: 

#head{ background: url(@url_image) no-repeat left top white;}

How can I assign a value at runtime?

标签: dotless
3条回答
SAY GOODBYE
2楼-- · 2019-08-08 04:23

When you say change dynamically in .less file, I am not sure why you wanna just change it in less file. If you just change it in .less file, you'll have to compile the file in order to navigative the change to style.min.css and style.css files, which you can't do programmatically.

This is what you can do:

 $('#head').css('background-image', "url("new-source");

So jquery/javascript is your best bet

查看更多
The star\"
3楼-- · 2019-08-08 04:44

There are a number of ways to do this. In my case, both the less content and dynamic parameters are stored in the DB. You can do something like this if you want to change a hex code color for example:

var parser = new dotless.Core.Parser.Parser();
var env = new dotless.Core.Parser.Infrastructure.Env { Compress = true, Debug = true, KeepFirstSpecialComment = false, DisableVariableRedefines = false };
var tree = parser.Parse(css.Detail.Text, null);

foreach (var key in layout.LessDetails.CurrentValues.Keys)
{
   var rule = tree.Variable("@" + key, tree);

   if (rule != null)
   {
      string value = layout.LessDetails.CurrentValues[key];

      if (value != null && value.StartsWith("#"))
      {
         rule.Value = new dotless.Core.Parser.Tree.Color(value.TrimStart('#'));
      }
   }
}

css.Detail.GeneratedText = tree.ToCSS(env);

This isn't an end all solution since there are many other types of parameters, but it should lead you in the right direction. Look in the dotless.Core.Parser.Functions for useful information on the various options.

Alternatively, there is another simple option. With the code above, you can simply append the changed variables to the end of the css.Detail.Text string. This is actually how the modifyVars method works in the less.js file. By adding the parameters again at the end, it overrides the previous set values.

查看更多
爷、活的狠高调
4楼-- · 2019-08-08 04:45

This can be done if you manually parse and output the dotless file.

var config = DotlessConfiguration.GetDefaultWeb();
config.DisableVariableRedefines = true;

string less = File.ReadAllText(fileName);
StringBuilder sb = new StringBuilder(less);
sb.AppendLine(string.Format("{0}: {1};", "@url_image", "image.jpg"));

return LessWeb.Parse(sb.ToString(), config);
查看更多
登录 后发表回答