将变量从 mixin 声明内部传递到附加的内容块中?

2024-03-06

在 Ruby 中,您可以轻松地将变量从方法内部传递到附加的代码块中:

def mymethod
  (1..10).each { |e| yield(e * 10) } # Passes a number to associated block
end

mymethod { |i| puts "Here comes #{i}" } # Outputs the number received from the method

我想在 SASS mixin 中做同样的事情:

=my-mixin
  @for $i from 1 to 8
    .grid-#{$i}
      @content

+my-mixin
  color: nth("red green blue orange yellow brown black purple", $i)

此代码不起作用,因为 $i 是在 mixin 声明内声明的,并且在使用 mixin 的外部无法看到。 :(

那么...我如何利用 mixin 声明中声明的变量?

当我使用网格框架和媒体查询时,我非常需要此功能。目前,我每次需要时都必须复制 mixin 声明中的内容,这违反了 DRY 规则。

更新2013-01-24

这是一个现实生活中的例子。

我有一个 mixin,可以循环断点并为每个断点应用一次提供的代码:

=apply-to-each-bp
  @each $bp in $bp-list
    +at-breakpoint($bp) // This is from Susy gem
      @content

当我使用这个 mixin 时,我必须在 @content 中使用这个 $bp 值。它可能是这样的:

// Applies to all direct children of container
.container > *
  display: inline-block

// Applies to all direct children of container,
// if container does not have the .with-gutters class
.container:not(.with-gutters) > *
  +apply-to-each-bp
    width: 100% / $bp

// Applies to all direct children of container,
// if container has the .with-gutters class
.container.with-gutters  > *
  +apply-to-each-bp
    $block-to-margin-ratio: 0.2
    $width: 100% / ($bp * (1 + $block-to-margin-ratio) - $block-to-margin-ratio)
    width: $width
    margin-right: $width * $block-to-margin-ratio

    &:nth-child(#{$bp})
      margin-right: 0

但这是行不通的,因为 $bp 的值在 @content 中不可用。

在调用 mixin 之前声明变量不会有帮助,因为 @content 在解析 mixin 之前解析一次。

相反,每次我需要的时候,我都必须做两条丑陋的大腿:

  1. 声明一个临时 mixin,
  2. 写循环,违反了DRY原则:
// Each of the following mixins is mentioned in the code only once.
=without-gutters($bp)
  width: 100% / $bp

=with-gutters($bp)
  $block-to-margin-ratio: 0.2
  $width: 100% / ($bp * (1 + $block-to-margin-ratio) - $block-to-margin-ratio)
  width: $width
  margin-right: $width * $block-to-margin-ratio

  &:nth-child(#{$bp})
    margin-right: 0

// Applies to all direct children of container
.container > *
  display: inline-block

// Applies to all direct children of container,
// if container does not have the .with-gutters class
.container:not(.with-gutters) > *
  @each $bp in $bp-list
    +at-breakpoint($bp) // This is from Susy gem
      +without-gutters($bp)

// Applies to all direct children of container,
// if container has the .with-gutters class
.container.with-gutters  > *
  @each $bp in $bp-list  // Duplicate code! :(
    +at-breakpoint($bp)  // Violates the DRY principle.
      +with-gutters($bp)

那么,问题是:有没有办法实现这种 Ruby 风格?


Sass 中的变量有scope给他们。它们仅在创建它们的块中可见。如果您希望变量可以在 mixin 内部和外部访问,则必须在全局范围内定义它:

$var: 0;

@mixin test {
    $var: $var + 1;
    color: red;
}

.test {
    $var: 5;
    @include test;
    @debug $var; // DEBUG: 6
}

只要你不关心状态$var很长一段时间以来,这应该可以满足您的目的。

对于您的示例,这不起作用,因为它看起来像@content首先被处理。你需要的是一个以不同方式编写的 mixin:

@mixin test($properties...) {
    @for $i from 1 to 8 {
        .grid-#{$i} {
            @each $p in $properties {
                $list: nth($p, 2);
                @if length($list) > 1 {
                    #{nth($p, 1)}: nth($list, $i);
                } @else {
                    #{nth($p, 1)}: $list;
                }
            }
            @content;
        }
    }
}

.test {
    @include test(color (red green blue orange yellow brown black purple));
}

生成的CSS:

.test .grid-1 {
  color: red;
}

.test .grid-2 {
  color: green;
}

.test .grid-3 {
  color: blue;
}

.test .grid-4 {
  color: orange;
}

.test .grid-5 {
  color: yellow;
}

.test .grid-6 {
  color: brown;
}

.test .grid-7 {
  color: black;
}

像这样的 mixin 可以提供任意数量的参数,并且仍然允许您使用@content如果你希望。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将变量从 mixin 声明内部传递到附加的内容块中? 的相关文章

随机推荐

  • 如何使用 AngularJS 创建可排序的手风琴?

    I found 用户界面可排序 https github com angular ui ui sortable并使其能够很好地处理简单的列表等 我的应用程序已经使用了ui引导程序 http angular ui github io boot
  • 使用 AirPrint 打印 PDF 会导致输出较小

    我尝试打印 pdfUIPrintInteractionController它加载在UIWevView 好消息是我可以打印 坏消息是打印输出太小 any help would be appreciated IBACTION printPDF
  • 如何将对象传递给 numpy 点函数

    假设我已经定义了我的对象 import numpy as np class myTensor def init self data self data np array data self parent 如何将 myTensor 作为输入传
  • Sphinx Pygments 词法分析器过滤器扩展?

    我有一种类似 Lisp 的语言 我想在 Sphinx 代码片段文档中强调使用 Pygments 我的方法是扩展现有的 CommonLispLexer 以使用 NameHighlightFilter 添加内置名称 但是 它不起作用 所以我一定
  • cordova - 失败:不支持 q

    当我构建 cordova 时 此消息视图 不支持使用 requireCordovaModule 加载非cordova模块 q 相反 将此模块添加到您的依赖项中并使用常规 require 来加载它 如何解决这个问题 附言 我在这个构建问题之前
  • Android SDK 管理器无法下载新文件

    我试图获取最新的 android 源代码 5 0 只是为了看看它看起来如何 但是当我尝试从 Android SDK 下载源代码时 它给了我一个错误 说local找不到网址 这是日志 Fetching https dl ssl google
  • 如何拉取已安装应用程序名称、包名称和可绘制图标的列表

    我试图弄清楚如何将此代码实现到我现有的源代码中 目前 我有一些源显示所有已安装应用程序的列表视图 单击将向应用程序发送意图 我需要一些关于如何拉出图标并将其添加到列表视图中的支持 任何帮助 源代码编辑 链接等都可以帮助我解决这个问题 谢谢
  • 使用node.js child_process调用python脚本

    我试图从我的节点文件调用 python 代码 这是我的node js代码 var util require util var spawn require child process spawn var process spawn pytho
  • 使用 nth-child 选择多个子元素

    div div p nth child 1 to 5 如何使用第 n 个子元素选择多个数字 这样我就可以获取子元素 1 到 5 而无需编写 div div p nth child 1 div div p nth child 2 div di
  • Firebird数据库SYSDBA连接错误

    我刚刚安装了 Win64 版 Firebird 并且尝试连接到用 ISQL 预打包的员工数据库 按照Firebird官方的步骤进行操作快速入门指南 https www firebirdsql org file documentation h
  • 如何制作带有渐变的曲线形状?

    I have to create image like this using CSS 如果不可能 那么我如何以最小的图像尺寸使用它 就像下面的代码一样 我使用了两个图像 但这也不起作用 div style background url ht
  • C# 如何判断一段时间内没有键盘或鼠标输入

    我正在尝试编写一行代码来检查在一分钟内是否没有来自键盘和鼠标的输入以及鼠标位置是否没有变化 如果此条件为真 则触发事件 if no Keyboard input no mouse input no change in mousePositi
  • Hystrix 命令失败并显示“超时并且没有可用的后备”

    我注意到我的应用程序中的某些命令失败了 Caused by com netflix hystrix exception HystrixRuntimeException GetAPICommand timed out and no fallb
  • Google App Engine 奇怪的延迟

    我改进了很多代码 现在所有 API 都运行得非常快 我还添加了内存缓存 并且命中率很高 但有时我会遇到毫无意义的延误 我在这里附上了最重要的 appstats 屏幕截图 运行 90 毫秒的 RPC 总共花费了 20 多秒 这怎么可能 我应该
  • Ionic + Angular 无法默认检查 ion-radio

    我正在尝试从单选列表中的单选按钮中检查一个 但没有运气 有人可以告诉我我做错了什么吗 谢谢你的帮助 我尝试通过这种方式做到这一点 div class list div
  • 使用用户名和密码克隆 github 的私人存储库

    我已经在我的系统上使用全局配置配置了帐户 A 我可以从那里克隆我的所有存储库 现在我不想更改配置 我想用我的用户名和密码克隆并执行帐户 B 的所有操作 我怎样才能做到这一点 我努力了 git clone username email pro
  • 实体框架 - 从数据库刷新对象

    我在刷新数据库中的对象时遇到问题 我有两台电脑和两个应用程序 在第一台 PC 上 有一个应用程序与我的数据库通信并向测量表添加一些数据 在我的另一台 PC 上 有一个应用程序可以在计时器下检索最新的测量值 因此它也应该检索由我的第一台 PC
  • 流帖子 URL 安全 - 网站/FB 页面 url

    我们目前在 iOS 和 Android 游戏应用程序中提供在 FB 上分享分数的功能 我们希望信息流帖子中的链接将人们引导至推广游戏的网站或 FB 上的游戏页面 我们在图中调用一些命令 流 发布 提供以下数据 link Settings F
  • JMSSerializerBundle 复杂生成值

    我需要在 symfony 2 上为我的网站实现 RESTful API 所以我使用 FOSRestBundle JMSSerializerBundle 我的实体有这样的序列化器 yml Acme DemoBundle Entity Prod
  • 将变量从 mixin 声明内部传递到附加的内容块中?

    在 Ruby 中 您可以轻松地将变量从方法内部传递到附加的代码块中 def mymethod 1 10 each e yield e 10 Passes a number to associated block end mymethod i