Is it possible to declare LESS variables in the HT

2019-09-21 06:38发布

问题:

Is it possible to declare LESS variables in the HTML and use the declared vars in a seperate .less file.

I want to do something like this:

<html>
<head>

<style type="text/less">
  @MYVAR: #9BC509;
</style>

<!-- use MYVAR inside the main.less file -->
<link rel="stylesheet/less" type="text/css" href="styles/less/main.less">

</head>
...
</html>

EDIT:

Since this did not work and was not a clean solution, I restructured my project, and now do a normal less file @incude for the variables I need. The less file is dynamically written to disc with database values by the django templating engine (and chached for better performance).

To all the downvoters. I don't really get your point! You didn't even write why you downvoted. I case you did not get what I was aiming for, here is the question I should have asked for "slow-thinkers":

How can I achieve including less variables declared in the <head></head> to be available in a seperate less file? But anyways this is just for people hitting this post at some point... As I said I chose another solution.

回答1:

You can do this by defining your variables in the globalVars property of a global less object. You should declare the less object before calling the less.js compiler, see also: http://lesscss.org/usage/#using-less-in-the-browser

<link rel="stylesheet/less" type="text/css" href="global.less">
<script>
    var less = {
    globalVars: {
      color: 'red',
      width: '15px'
    }
    }
</script>
<script src="js/less.min.js" type="text/javascript"></script>

The preceding enables you to use @color and @width in the Less code of global.less.



回答2:

You can define them on the less.js script tag like this:

<script src="/js/less.js" data-global-vars='{ "color1": "#333" }' rel="stylesheet/less"></script>

So, for php you can do:

<script src="/less.js" data-global-vars='<?php 
      echo json_encode([
                       'color1' => '#F0CF5B',
                ])
?>' rel="stylesheet/less"></script>


回答3:

You can't. What you can do is give a class name to your (or any other high level container) and then define multiple values based on that:

.home {
  @MYVAR: #9BC509;
}

.page {
  @MYVAR: #fff;
}

Or use LESS guards (see LESS docs)