You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Gulp从options.json调用Sass变量?Twig调用已实现

Answer

Absolutely—you can absolutely use a single options.json file to power both your Twig templates and Sass variables. The issue with existing plugins is that they don’t handle edge cases like URLs or references to existing Sass variables (like your $gradient-4). Here’s a custom, flexible solution that gives you full control:

Step 1: Create a Gulp Task to Generate Sass Variables from JSON

Instead of relying on finicky plugins, we’ll write a simple task that reads your options.json, extracts the sass section, and writes it into a reusable Sass partial. This lets us handle URLs, numeric values, and Sass variable references correctly.

Add this to your gulpfile.js:

const gulp = require('gulp');
const fs = require('fs');
const path = require('path');

// Task to generate Sass variables from options.json
gulp.task('generate-sass-vars', (done) => {
  // Path to your options.json
  const optionsPath = path.join(__dirname, 'app/options.json');
  const options = JSON.parse(fs.readFileSync(optionsPath, 'utf8'));
  const sassConfig = options.sass || {};

  let sassContent = '// Auto-generated variables (do not edit manually)\n';

  // Loop through each key-value pair in the sass section
  Object.entries(sassConfig).forEach(([key, value]) => {
    let processedValue = value;

    // Handle existing Sass variable references (e.g., $gradient-4)
    if (typeof value === 'string' && value.startsWith('$')) {
      processedValue = value;
    }
    // Wrap URLs in quotes to avoid Sass syntax errors
    else if (typeof value === 'string' && (value.startsWith('http') || value.includes('/'))) {
      processedValue = `"${value}"`;
    }
    // Convert numeric strings (like ".5") to actual numbers
    else if (!isNaN(parseFloat(value)) && isFinite(value)) {
      processedValue = parseFloat(value);
    }
    // Wrap other strings in quotes
    else if (typeof value === 'string') {
      processedValue = `"${value}"`;
    }

    // Generate the variable name (e.g., bgOpacity becomes $sass-bgOpacity)
    const varName = `$sass-${key}`;
    sassContent += `${varName}: ${processedValue};\n`;
  });

  // Write to a Sass partial (save this in your Sass src folder)
  fs.writeFileSync(path.join(__dirname, 'src/sass/_generated-vars.scss'), sassContent);
  done();
});

Step 2: Import the Generated Variables into Your Sass

In your main Sass file (e.g., main.scss), import the auto-generated partial:

// Import auto-generated variables first
@import 'generated-vars';

// Now you can use the variables just like any other Sass variable
$opacity: $sass-bgOpacity;
$hero-bg-image: $sass-bgPicture;
$hero-bg-color: $sass-bgColor;

body {
  background: $hero-bg-color url($hero-bg-image) no-repeat center/cover;
  opacity: $opacity;
}

Step 3: Integrate the Task into Your Gulp Workflow

Update your Sass compilation task to run generate-sass-vars first, so the variables are always up-to-date:

const sass = require('gulp-sass')(require('sass')); // Or node-sass, depending on your setup

gulp.task('compile-sass', gulp.series('generate-sass-vars', () => {
  return gulp.src('src/sass/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('dist/css'));
}));

Step 4: Add a Watcher for Options.json

To automatically regenerate variables when you update options.json, add a watch task:

gulp.task('watch', () => {
  // Regenerate Sass vars and recompile when options.json changes
  gulp.watch('app/options.json', gulp.series('compile-sass'));
  // Keep your existing watchers for Twig/Sass files
  gulp.watch('src/twig/**/*.twig', gulp.series('compile-twig'));
  gulp.watch('src/sass/**/*.scss', gulp.series('compile-sass'));
});

Why This Works

  • Full Control: Unlike plugins, we explicitly handle URLs (wrap in quotes), Sass variable references (pass through as-is), and numeric strings (convert to numbers).
  • Single Source of Truth: Your options.json drives both Twig templates and Sass variables, so you only need to update values in one place.
  • No Plugin Limitations: Avoids the issues you ran into with plugins that can’t handle non-standard JSON values for Sass.

This setup will let you use variables like $sass-bgOpacity in your Sass exactly as you wanted, while keeping your Twig workflow intact.

内容的提问来源于stack exchange,提问作者uokersam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:22:28