Home >Web Front-end >CSS Tutorial >Validating Input in Sass Mixins and Functions
Core points
type-of()
, unit()
, and unitless()
. These functions can be used to check the type and unit of the input data, and an error will be thrown if the input does not meet the expected criteria. @function
directive and returning a value based on the verification check using the @return
directive. @error
directive can be used to throw a custom error message, providing detailed information about the nature of the error and how to fix the error. When writing Sass and using it by others, they are likely to make an error while using your code. In fact, honestly, when I write Sass and use it a few days (or even hours later), I make mistakes in my own code. You might, too. Fortunately, Sass has many functions that can help us verify the input developers put into Sass we wrote.
These technologies are especially useful for teams that share Sass mixin or maintain a starter kit or a set of mixin and functions. Developers have two options when using shared Sass libraries: they can interrupt each other by email, chat, ping, or otherwise for help with custom mixin help, or use detailed documentation that includes code verification to help each other easily exclude them. Code failure. (For this point, it's not just a problem with Sass: any shared code needs to communicate via interrupts or documents.) Now let's learn some of the most useful methods of Sass verification.
Verify a single value
Mixin and function take parameters. If you pass the code to other developers at work or publish open source libraries, you need to make sure the parameters match your intent. These functions are useful for verifying variables in parameters.
variable-exists()
If your function or mixin depends on a developer-defined variable, use the appropriate variable-exists()
function to ensure that the variable exists. This function returns true or false based on whether the variable has been created and defined.
<code class="language-sass">@mixin create-font-size() { @if variable-exists(base-font) { font-size: $base-font; } @else { @error "请定义变量 `$base-font`。"; } @if variable-exists(line-height) { line-height: $line-height; } @else { @error "请定义变量 `$line-height`。"; } } // 开发者的代码 $base-font: 18px; $line-height: 1.5; .element { @include create-font-size; }</code>
However, a better option than relying on developers to set global variables correctly is to include these default variables in your library:
<code class="language-sass">// 你的插件: $base-font: 18px !default; $line-height: 1.5 !default; @mixin create-font-size() { //等等... } // 开发者的代码: $base-font: 16px; p { @include create-font-size(); }</code>
type-of()
If you need to know the type of value represented by a variable, please use type-of()
. This function will return one of the following strings:
This is useful for verifying certain types of inputs. You can make sure that the developer passes only the values to the mixin that creates the size:
<code class="language-sass">@mixin create-font-size() { @if variable-exists(base-font) { font-size: $base-font; } @else { @error "请定义变量 `$base-font`。"; } @if variable-exists(line-height) { line-height: $line-height; } @else { @error "请定义变量 `$line-height`。"; } } // 开发者的代码 $base-font: 18px; $line-height: 1.5; .element { @include create-font-size; }</code>
You can also use type-of()
to ensure that the color mixin only processes colors:
<code class="language-sass">// 你的插件: $base-font: 18px !default; $line-height: 1.5 !default; @mixin create-font-size() { //等等... } // 开发者的代码: $base-font: 16px; p { @include create-font-size(); }</code>
If you need developers to create configuration settings maps for themes, you can make sure they have valid maps:
<code class="language-sass">@mixin size($height, $width: $height) { @if type-of($height) == number { height: $height; } @else { @warn "确保 `$height` 是一个数字。"; } @if type-of($width) == number { width: $width; } @else { @warn "确保 `$width` 是一个数字。"; } }</code>
unit()
Sometimes, mathematical operations in functions or mixin require specific units in their parameters. You can use unit()
to confirm that the value has the correct unit. For example, you might use a mixin to create pixel and rem unit dimensions. (Note that you'd better run the package with a task for this, but if you need to keep it in Sass, keep reading.)
<code class="language-sass">@function color-fade($color) { @if type-of($color) == 'color' { @return rgba($color, .8); } @else { @warn "确保你将有效的颜色传递给 color-fade() 函数。"; } }</code>
Verify list and map
We have seen how to use type-of()
to make sure that variables contain lists or maps. We can also test two important things: whether the values are in the list, and whether the keys are in the map.
index()
index()
function will tell you whether the value is found in the list. Technically, it will return the position of the value in the list (a number) or null. It's not a true Boolean function, but for our purpose here, true and false values are sufficient.
index()
The function takes two parameters: the list and the value you want to find in the list. This function is useful for testing measurements of certain values in a mixin. If we have a mixin that outputs padding or margin calculations using CSS top, right, bottom, or left shorthand, we want to make sure we don't try to calculate values like initial, inherit, or auto.
<code class="language-sass">@mixin generate-theme($settings) { @if type-of($settings) == 'map' { // 此处输出 } @else { @warn "确保 `$settings` 是一个 Sass 映射。"; } }</code>
map-has-key()
If you are checking for a specific key in the map, you can use the map-has-key()
function to ensure that the key exists in the map you are checking for. This will be very useful if you use $breakpoints
mapping and media query mixin:
<code class="language-sass">$rem-size: 16px !default; @mixin px-rem($property, $value) { @if unit($value) == 'px' { #{$property}: $value; #{$property}: $value / $rem-size * 1rem; } @elseif unit($value) == 'rem' { #{$property}: $value * $rem-size / 1rem; #{$property}: $value; } @else { @warn "确保 `$value` 以 px 或 rem 为单位。"; } }</code>
Verify Mixin and functions
Sometimes you will write a mixin or function that depends on an existing mixin or function or other Sass library. Let's update the bp()
mixin from the previous example to rely on the Breakpoint Sass library. We can extend it like this:
<code class="language-sass">$rem-size: 16px !default; @mixin margin-rem($values...) { $output: (); @each $value in $values { @if index(auto inherit initial 0, $value) { $output: append($output, $value); } @else { $output: append($output, $value / $rem-size * 1rem); } } margin: #{$output}; }</code>
Now our bp()
mixin (shorter and uses mapped values) will use breakpoint()
mixin when it exists. If not, it will fall back to our own media query mixin code.
There is a matching function called function-exists()
. You can use it to test whether a specific function exists. If you have math operations that rely on non-standard functions, you can make sure to include libraries that contain the function. Compass added a pow()
function for exponential mathematics. If you are creating a font size ratio that requires the function, test it:
<code class="language-sass">@mixin create-font-size() { @if variable-exists(base-font) { font-size: $base-font; } @else { @error "请定义变量 `$base-font`。"; } @if variable-exists(line-height) { line-height: $line-height; } @else { @error "请定义变量 `$line-height`。"; } } // 开发者的代码 $base-font: 18px; $line-height: 1.5; .element { @include create-font-size; }</code>
Reporting questions: @warn
and @error
. This directive sends messages to the developer's console, but allows the compiler to complete the run. @warn
to send the message to the console and stop the compiler. @error
and @warn
, you may want to check out my previous article on this topic or the corresponding section in the Sass reference for SitePoint. @error
Conclusion
No one is perfect—those who use our code are not, and not even ourselves after we write our code for a few hours! This is why it is very important to help ourselves and others by validating inputs in mixin and functions. These techniques not only help you use your own code more efficiently, but also make it easier for teams to share and maintain Sass libraries.How do you prevent errors in Sass? Please let us know in the comments!
FAQs (FAQ) on Verifying Inputs in Sass Mixin and Functions
What is the purpose of verifying input in Sass mixin and functions?How do I verify input in Sass mixin and function?
, type-of()
and unit()
, etc. You can use these functions to check the type and unit of the input data, and an error will be thrown if the input does not meet the expected criteria. For example, you can use the unitless()
function to check if the input is a number, and if not, an error will be thrown. type-of()
Yes, you can create custom validation functions in Sass. This is very useful if you need to perform more complex validation checks that cannot be implemented using built-in functions. To create a custom validation function, simply define a new function using the @function
directive, and then use the @return
directive to return a value based on the validation check.
If the input validation in Sass mixin or function fails, an error will be thrown and compilation of the Sass code will stop. This can help you quickly identify and correct any issues in the input data and prevent bugs and errors in the final CSS output.
Sass provides the @error
directive, which you can use to throw a custom error message when the input verification fails. This is especially useful for debugging, as you can provide detailed information about the nature of the error and how to fix it.
Yes, the Sass introspection function can be used for input validation. These functions allow you to check the type, unit, and other properties of the input data, and can be used in conjunction with the @error
directive, which can throw a custom error message when the input does not meet the expected criteria.
Verify that the input can be used in a variety of scenarios in Sass mixin and functions. For example, you might want to make sure that the color value passed to the mixin is a valid color, or that the number passed to the function has the correct unit. Input validation can also be used to enforce certain constraints or rules in code, such as ensuring that a certain parameter is always provided, or that a value is within a specific range.
Yes, you can use the mixin-exists()
function to test whether the mixin exists in Sass. If mixin exists, this function returns true, otherwise false. This is very useful for preventing errors in your code, as you can check if the mixin exists before trying to include it.
unit()
function for input validation in Sass? function in unit()
in Sass returns the unit of a number. You can use this function in input validation to check if the number has the correct unit. For example, you might want to make sure that the length value passed to the mixin is in pixels, or the time value passed to the function is in seconds.
Some best practices for validating inputs in Sass mixin and functions include: Always verifying input data; using built-in Sass functions whenever possible to verify; creating custom verification functions for more complex checks; throwing using the @error
directive Customize the error message; and thoroughly test your code to make sure the verification check works properly.
The above is the detailed content of Validating Input in Sass Mixins and Functions. For more information, please follow other related articles on the PHP Chinese website!