定制 csabourin/meteocraft 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

csabourin/meteocraft

最新稳定版本:v2.1.1

Composer 安装命令:

composer require csabourin/meteocraft

包简介

Simple CraftCMS plugin for displaying Ottawa weather from Environment Canada with a front-end Twig template

README 文档

README

Simple, accessible weather display component for Ottawa, Ontario, using data from Environment and Climate Change Canada (ECCC). Built for Craft CMS 5 with PHP in Twig support.

Features

  • Self-Contained: Single Twig template with embedded PHP - no plugin required
  • Current Weather: Real-time temperature, humidity, wind, pressure, and conditions
  • Today's Forecast: Weather breakdown by time period (morning, afternoon, evening)
  • Bilingual: Full English and French support with translations
  • Accessible: WCAG 2.1 AA compliant with semantic HTML and ARIA labels
  • Customizable: SCSS file with variables for easy theming
  • Cached: 30-minute cache to optimize API calls
  • Official Data: Environment and Climate Change Canada API

Requirements

  • Craft CMS 5.x
  • PHP 8.0 or higher
  • PHP in Twig (Twig Perversion) enabled
  • cURL extension

Installation

1. Copy Files to Your Craft Project

Copy the files from this repository to your Craft installation:

# From this repository root, copy to your Craft project:
cp -r templates/_weather /path/to/your/craft/templates/
cp -r assets/scss /path/to/your/craft/assets/  # or wherever you keep SCSS
cp -r translations /path/to/your/craft/modules/yourmodule/  # or your module directory

2. Register Translations in Your Module

Add the translation category to your module's config/app.php:

return [
    'modules' => [
        'yourmodule' => \modules\yourmodule\Module::class,
    ],
    'components' => [
        'i18n' => [
            'translations' => [
                'weather' => [
                    'class' => craft\i18n\PhpMessageSource::class,
                    'sourceLanguage' => 'en',
                    'basePath' => '@modules/yourmodule/translations',
                    'allowOverrides' => true,
                ],
            ],
        ],
    ],
];

Or if you prefer, add it directly in your module's init() method:

public function init()
{
    parent::init();

    Craft::$app->i18n->translations['weather'] = [
        'class' => PhpMessageSource::class,
        'sourceLanguage' => 'en',
        'basePath' => __DIR__ . '/translations',
        'allowOverrides' => true,
    ];
}

3. Import SCSS

Add to your main stylesheet:

// In your main.scss
@import 'path/to/assets/scss/weather';

Customize Colors

Define variables before importing:

// Custom colors
$meteocraft-primary-color: #0066cc;
$meteocraft-background: #f8f9fa;
$meteocraft-border-color: #dee2e6;
$meteocraft-text-color: #212529;
$meteocraft-border-radius: 8px;

// Import styles
@import 'path/to/assets/scss/weather';

Usage

Basic Usage

Include the template anywhere in your Twig files:

{% include '_weather/display' %}

With Options

{% include '_weather/display' with {
    city: 'Ottawa',
    lang: 'fr'
} %}

Example Integrations

In a Layout

{# templates/_layout.twig #}
<!DOCTYPE html>
<html lang="{{ currentSite.language }}">
<head>
    <title>{{ siteName }}</title>
    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body>
    <aside class="weather-sidebar">
        {% include '_weather/display' %}
    </aside>

    <main>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

In a Page Template

{# templates/index.twig #}
{% extends "_layout" %}

{% block content %}
    <h1>Welcome</h1>

    <section class="weather-widget">
        <h2>Current Weather in Ottawa</h2>
        {% include '_weather/display' %}
    </section>
{% endblock %}

File Structure

/your-craft-project/
├── templates/
│   └── _weather/
│       └── display.twig          # Main weather display template
├── assets/
│   └── scss/
│       └── _weather.scss          # Styles with variables
└── modules/
    └── yourmodule/
        └── translations/
            ├── en/
            │   └── weather.php    # English translations
            └── fr/
                └── weather.php    # French translations

Configuration

Cache Duration

Edit the PHP block in templates/_weather/display.twig:

// Find this line (around line 145):
$cache->set($cacheKey, $weatherData, 1800);

// Change 1800 (30 minutes) to your desired duration in seconds:
$cache->set($cacheKey, $weatherData, 3600); // 1 hour

Customizing Display

The template is fully editable. Modify templates/_weather/display.twig to:

  • Change layout and styling
  • Add or remove weather data points
  • Adjust time periods (currently: morning 6am-12pm, afternoon 12pm-6pm, evening 6pm-12am)

Translations

Edit the translation files to customize any text:

  • translations/en/weather.php - English
  • translations/fr/weather.php - French

Data Source

  • API: Environment and Climate Change Canada (ECCC)
  • Endpoint: https://api.weather.gc.ca/collections/citypageweather-realtime
  • Documentation: ECCC Open Data
  • Location: Ottawa (Kanata - Orléans)

Accessibility

This component is WCAG 2.1 Level AA compliant:

  • ✓ Proper semantic HTML5 elements
  • ✓ ARIA labels and roles
  • ✓ Keyboard accessible
  • ✓ Screen reader friendly
  • ✓ High contrast ratios (4.5:1+)
  • ✓ Bilingual support

See ACCESSIBILITY.md for details.

Troubleshooting

Template shows "Unable to load weather data"

  1. Verify server has internet connectivity
  2. Check cURL is enabled: php -m | grep curl
  3. Ensure PHP in Twig is enabled in your Craft config
  4. Check logs: storage/logs/web.log
  5. Clear cache: ./craft clear-caches/all

Translations not working

  1. Verify translations are registered in config/app.php or your module
  2. Check file paths match your module structure
  3. Clear cache: ./craft clear-caches/all
  4. Verify translation category is 'weather' (not 'meteocraft')

Styling not applied

  1. Verify SCSS file is imported in your main stylesheet
  2. Check file path is correct
  3. Rebuild your CSS: npm run build or your build command
  4. Clear browser cache

License

MIT License - see LICENSE file

Credits

Support

For issues or questions: GitHub Repository

Alternative: Using with Your Existing Controller

If you prefer to use your existing controller's actionFetchJson() method instead of the embedded PHP, you can modify the template to make an AJAX call:

{# In templates/_weather/display.twig, replace the {% php %} block with: #}
<div class="meteocraft-weather-display" data-url="{{ url('external-api-data/data/fetch-json', {
    url: 'https://api.weather.gc.ca/collections/citypageweather-realtime/items?f=json&limit=1&q=Ottawa'|url_encode
}) }}">
    <div class="loading">Loading weather data...</div>
</div>

{# Add JavaScript to fetch and render #}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const container = document.querySelector('.meteocraft-weather-display');
    const url = container.dataset.url;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            // Parse and render weather data
            // ... your rendering logic
        });
});
</script>

However, note that your current controller only allows services2.arcgis.com in the allowlist, so you'd need to add api.weather.gc.ca to use it for weather data.

统计信息

  • 总下载量: 10
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: Twig

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-02