Как в sassscript выглядит валидный синтаксис интерполяции

от admin

Interpolation

Interpolation can be used almost anywhere in a Sass stylesheet to embed the result of a SassScript expression into a chunk of CSS. Just wrap an expression in #<> in any of the following places:

SCSS Syntax

Sass Syntax

CSS Output

In SassScript permalink In SassScript

LibSass and Ruby Sass currently use an older syntax for parsing interpolation in SassScript. For most practical purposes it works the same, but it can behave strangely around operators. See this document for details.

Interpolation can be used in SassScript to inject SassScript into unquoted strings. This is particularly useful when dynamically generating names (for example for animations), or when using slash-separated values. Note that interpolation in SassScript always returns an unquoted string.

SCSS Syntax

Sass Syntax

CSS Output

�� Fun fact:

Interpolation is useful for injecting values into strings, but other than that it’s rarely necessary in SassScript expressions. You definitely don’t need it to just use a variable in a property value. Instead of writing color: # <$accent>, you can just write color: $accent !

⚠️ Heads up!

It’s almost always a bad idea to use interpolation with numbers. Interpolation returns unquoted strings that can’t be used for any further math, and it avoids Sass’s built-in safeguards to ensure that units are used correctly.

Sass has powerful unit arithmetic that you can use instead. For example, instead of writing #<$width>px , write $width * 1px —or better yet, declare the $width variable in terms of px to begin with. That way if $width already has units, you’ll get a nice error message instead of compiling bogus CSS.

Quoted Strings permalink Quoted Strings

In most cases, interpolation injects the exact same text that would be used if the expression were used as a property value. But there is one exception: the quotation marks around quoted strings are removed (even if those quoted strings are in lists). This makes it possible to write quoted strings that contain syntax that’s not allowed in SassScript (like selectors) and interpolate them into style rules.

SCSS Syntax

Sass Syntax

CSS Output

⚠️ Heads up!

While it’s tempting to use this feature to convert quoted strings to unquoted strings, it’s a lot clearer to use the string.unquote() function. Instead of # <$string>, write string.unquote($string) !

  • Current Releases:
  • Dart Sass 1.59.2
  • LibSass 3.6.5
  • Ruby Sass ⚰
  • Implementation Guide

Sass © 2006–2023 the Sass team, and numerous contributors. It is available for use and modification under the MIT License.

Как в sassscript выглядит валидный синтаксис интерполяции

Kitty Giraudel Jun 24, 2014

So you play with Sass from time to time. You’re starting to enjoy it since it caters to most of your needs. But there’s this one thing you don’t completely understand: interpolation — slotting values into other values. Well you’re in luck, because today I’m going to shed some light on the matter.

Interpo. What?

Interpolation, often referred to as variable interpolation or variable substitution is not something unique to Sass. Actually, you can find it in many languages (PHP, Perl, Ruby, Tcl, Groovy, Unix shells. ). We often talk about interpolating a variable or interpolating an expression. To put it concisely, interpolating is the process of evaluating an expression or a string containing one or more variables, yielding a result in which the variables are replaced with their corresponding values in memory.

Let’s take a look at an example instead. If you have some basic knowledge of PHP this might be easier to grasp. Let’s say you want to echo a string which contains a variable. The common way is to do this:

This is not interpolation. This is string-concatenation. Basically we are concatenating (chaining together) three strings: «Tuts+ is » , «awesome» (referenced as $description ) and «!» . Now, we could use interpolation rather than string concatenation:

The braces around the variable tells PHP to print the variable value within the string. Note that it needs double quotes to work in PHP (which is true of most languages).

Anyway, this is variable/expression interpolation. Whether you use concatenation or interpolation is really up to you at this point, but let’s just say that interpolation is syntactic sugar for string concatenation.

Sweet.

What About Sass?

Let’s have a look at how variable substitution works in Sass.

Sass variable names, just like in PHP, are prefixed with the dollar sign ( $ ). This is where the comparison ends though, because when it comes to interpolation, Sass and PHP behave differently. There is a good reason for this: Sass is built in Ruby, which uses # for expression substitution.

In Sass, you’d do the following:

Note that the $ sign is not subtracted from the variable name like in PHP. The variable is simply encapsulated in # . It’s also worth noting you can interpolate any variable type, not only strings. For instance:

When Should I Use Interpolation?

Now that you are aware of what variable interpolation is and how to do it in Sass, it’s time to move on to actual use cases. For the first one, we will reuse what we just did with the @warn directive, which prints content to the console.

Strings

Let’s say you have a map of colors called $colors (a map is a variable which stores a mix of key/value pairs) but you’re tired of typing map-get($colors, . ) over and over again, so you build a little color() function fetching the color mapped to whatever key is passed. Let’s write the basics together:

So that’s pretty nice, right? Now you’d like to warn yourself that the key doesn’t exist if you make a typo or are trying to fetch an unknown key from the map (by the way, you might want to read this introduction to error handling in Sass.) This is done through the @warn directive, in the color() function.

Not bad. Now what if you want to identify which key has not been found?

Boom, variable interpolation. Calling color(awesomeness) will throw out the following message in the console:

That’s cool, but we don’t really know what the context is. To help our future selves, we could add the map name within the error message.

In this case, since the $colors variable has not been interpolated, it will be printed as a string.

Key awesomeness not found in $colors map.

CSS Functions

So far, we have seen the most common case for variable substitution: printing the content of a variable in a string. That’s a great example, but it has occurred to me there is an even better case for this: variables in CSS functions, for instance calc() .

Let’s say you want to size your main container based on the width of the sidebar. As you are a conscientious front-end developer, you have stored this width in a variable, so you can do this:

And then surprise! It doesn’t work. There’s no Sass error, but your container isn’t sized properly. If you go and inspect its styles with DevTools, you’ll see this — crossed out because it’s invalid:

Now let’s think about it: calc() is a CSS function, not a Sass function. This means that Sass interprets the whole expression a string. You can try it:

Because it is a string, there is no reason for Sass to behave any differently than earlier with $colors in our @warn string. $sidebar-width is considered to be a regular string, so gets printed as is. But that’s not what you want, right? So let’s interpolate it!

Now, when Sass compiles the stylesheet, it will replace # with the value associated to $sidebar-width , in this case 250px , resulting in the following valid CSS expression:

Mission accomplished! We talked about calc() here but it’s the same thing with url() , linear-gradient() , radial-gradient() , cubic-bezier() and any other CSS native functions, including all the pseudo-classes.

Here’s another example using CSS functions:

This is a case you’ve possibly encountered: using a for loop in conjunction with :nth-*() selectors. Once again, you need to interpolate the variable so it gets printed in the output CSS.

Читать:
Bt sideband device драйвер что это

To sum up: Sass treats CSS functions as strings, thus requiring you to escape any variable used within them in order to print their value in the resulting CSS.

CSS Directives

Let’s move on with another interesting case for variable interpolation: CSS directives, like @support , @page but most importantly @media .

Now, this has to do with how Sass parses CSS at-directives, especially the media directive. I’ve been sniffing through Sass code, and while my Ruby is really not that good, I managed to find something interesting:

Basically, the first lines here tell Sass to return the media query if there is an interpolated expression, or an error unless it finds an opening brace ( ( ), in which case it should keep going and parse the whole thing. Let’s try an example here:

Unsurprisingly, this fails:

Invalid CSS after «@media «: expected media query (e.g. print, screen, print and screen), was «$value

As the error message points out, it is expecting a media query. At this point, you have to interpolate your variable if it comes right after the @media string. For instance:

As we’ve deduced from our Ruby escapade earlier, if @media is directly followed by braces ( () ), you don’t have to interpolate the variable anymore because Sass will evaluate anything inside those braces. For instance:

In this case, Sass evaluates the expression (max-width: $value) , turning it into (max-width: 1337px) yielding a valid CSS result, so there is no need to escape the variable.

As for why Sass maintainers design it like this, I asked Nathan Weizenbaum. Here is his reply:

In general, we don’t like allowing raw variables in places where full SassScript expressions can’t be used. Media queries are such a place, since SassScript can be ambiguous there (maps especially).

— Nathan Weizenbaum (@nex3) June 10, 2014

Selectors

Okay, this is the last example of a use case where you need to interpolate Sass variables: when using a variable as a selector, or as part of a selector. While it might not be an everyday use case, it is not uncommon to do something like this:

Unfortunately, this doesn’t work:

This is pretty much for the same reasons as for the media query example. Sass has its own way of parsing a CSS selector. If it encounters something unexpected, for instance an unescaped dollar sign, then it crashes.

Fortunately, solving this issue is simple (and you know the solution by now): interpolate the variable!

Final Thoughts

In the end, Sass interpolation is not as simple as it might seem. There are some cases where you have to escape your variables, and some where you don’t. From there, you have two ways of doing things:

  • either you wait for an error message, then you escape
  • or you escape everywhere but in regular CSS values (where you know it works great).

Anyway, I hope I’ve helped you understand how variable interpolation works. If you have anything to add, be sure to share in the comments.

What’s Interpolation in SCSS (Sass)?

Interpolation is nothing but an expression wrapped in #<>.

You can use it anywhere in your SCSS stylesheet. You need that to embed the result of a SassScript expression.

What’s SassScript expression?

SassScript expression is the the part on the right side of a variable or property declaration.

Those are some simple examples. It can get very complex and powerful.

Each SassScript expression produces a value on compilation. You can also use valid CSS property value (like 40px in the example above) as a SassScript expression.

When you pass the SassScript expression as arguments in mixin or functions, it can produce some amazing results with fewer lines of code. You can also use @if rule to manipulate it.

Where can you use Interpolation?

Since it’s just like a variable declaration, so you can use it like the following examples:

Interpolation in style rules

After compilation, this is what we get in CSS:

Interpolation in Property Declarations

After compilation, this is what we get in CSS:

Where else can you use interpolation?

You can use it wherever you like. For e.g use it in comments or in property values or in at-rules or with @extends or @imports. You can also use it with strings(quoted or unquoted), in special functions or just in a simple functions.

Do I HAVE to use interpolation?

Interpolation can mostly be used in injecting values into strings other than that you can live without it!

For e.g. you don’t need interpolation to declare a property with a variable value. Like this:

DO NOT use interpolation with numbers

You MUST not use interpolation with numbers since it returns the value as a string.

If you use a interpolation with numbers then the math won’t work since you’ll be using strings.

For math operations, use unit arithmetic instead.

For e.g. instead of this:

You can always define the variable with the unit. That’s the best solution suggested by Sass.

Interpolation will remove quotes around strings

Till now, we understood that interpolation injects the same exact value. Nah! It has one exception. It will remove the quotes around the string. Like this:

This CSS code we get after compilation:

Quotes will be removed no matter how you pass the string, direct string or via lists. No quotes! Sass (SCSS) doesn’t believe in motivation, does it?

Sass explains their move by stating that it allows us to write strings with quotes that can contain a syntax which is actually not allowed in SassScript! That way it uses interpolation to interpolate them into valid style rules.

Интерполяция

Интерполяцию можно использовать практически в любом месте таблицы стилей Sass, чтобы встроить результат выражение SassScript в фрагмент CSS. Просто заключите выражение в #<> в любом из следующих мест:

SCSS Syntax

Sass Syntax

CSS Output

В SassScript permalink В SassScript

LibSass и Ruby Sass в настоящее время используют старый синтаксис для анализа интерполяции в SassScript. Для большинства практических целей он работает так же, но может вести себя странно с операторами. Смотрите этот документ для получения подробной информации.

В SassScript можно использовать интерполяцию для внедрения SassScript в [строки без кавычек]unquoted strings. Это особенно полезно при динамическом создании имен (например, для анимации) или при использовании значений, разделенных косой чертой. Обратите внимание, что интерполяция в SassScript всегда возвращает строку без кавычек.

SCSS Syntax

Sass Syntax

CSS Output

�� Интересный факт:

Интерполяция полезна для вставки значений в строки, но в остальном она редко требуется в выражениях SassScript. Вам определенно не нужно просто использовать переменную в значении свойства. Вместо того, чтобы писать color: # <$accent>, вы можете просто написать color: $accent !

⚠️ Внимание!

Практически всегда использовать числовую интерполяцию — плохая идея. Интерполяция возвращает строки без кавычек, которые нельзя использовать для дальнейших вычислений, и избегает встроенных мер безопасности Sass, чтобы гарантировать правильное использование единиц измерения.

В Sass есть мощная арифметика единиц, которую вы можете использовать вместо этого. Например, вместо того, чтобы писать #<$width>px , напишите $width * 1px или, еще лучше, объявите переменную $width в терминах px для начала. Таким образом, если у $width уже есть единицы измерения, вы получите красивое сообщение об ошибке вместо компиляции поддельного CSS.

Процитированные строки permalink Процитированные строки

В большинстве случаев интерполяция вводит тот же текст, который использовался бы, если бы выражение использовалось как значение свойства. Но есть одно исключение: кавычки вокруг цитируемых строк удаляются (даже если эти цитируемые строки находятся в списках). Это позволяет писать строки в кавычках, содержащие синтаксис, недопустимый в SassScript (например, селекторы), и интерполировать их в правила стиля.

SCSS Syntax

Sass Syntax

CSS Output

⚠️ Внимание!

While it’s tempting to use this feature to convert quoted strings to unquoted strings, it’s a lot clearer to use the string.unquote() function. Instead of # <$string>, write string.unquote($string) !

  • Текущие релизы:
  • Dart Sass 1.49.0
  • LibSass 3.6.5
  • Ruby Sass ⚰
  • Руководство по внедрению

Sass © 2006–2022 команда Sass и многочисленные участники. Он доступен для использования и модификации по лицензии MIT .

Похожие статьи