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

Django CMS:如何管理HTML类渲染并移除多余插件占位类

Removing Auto-Generated CMS Classes in Django CMS

Great question! Those auto-added cms-plugin-* and cms-placeholder-* classes can clutter up your HTML when you’re aiming for a clean, custom frontend. Here are several practical ways to tackle this, plus details on configuration and custom rendering options:

1. Override Default Django CMS Templates

Django CMS relies on templates to render plugins and placeholders, so you can directly modify these templates to strip out unwanted classes.

  • For Placeholders: Locate the default placeholder template (typically found at cms/templates/cms/toolbar/placeholder.html in the Django CMS package). Copy this file into your project’s templates/cms/toolbar/ directory, then edit the wrapper element to remove the cms-placeholder and cms-placeholder-{id} classes.
  • For Plugins: Most core plugins have dedicated templates (e.g., cms/plugins/text.html for the text plugin). Copy the template you want to adjust into your project’s template structure, then delete the cms-plugin and cms-plugin-{id} classes from the outer container.

This approach is straightforward if you only need to tweak specific plugins or placeholders.

2. Custom Plugin Base Class with Modified Rendering

For a global solution across all your plugins, create a custom base plugin class that overrides the default rendering behavior to exclude those classes.

Here’s a quick example:

from cms.plugin_base import CMSPluginBase

class NoClassCMSPluginBase(CMSPluginBase):
    def render(self, context, instance, placeholder):
        context = super().render(context, instance, placeholder)
        # Strip auto-added plugin classes from the context
        if 'css_classes' in context:
            context['css_classes'] = context['css_classes'].replace('cms-plugin', '').replace(f'cms-plugin-{instance.pk}', '')
        return context

Then have all your custom plugins inherit from NoClassCMSPluginBase instead of CMSPluginBase. This ensures none of your plugins output the unwanted classes.

3. Django Middleware to Clean HTML Responses

For a "set it and forget it" solution that works across all plugins and placeholders, use a middleware to modify the HTML response before it’s sent to the client.

You’ll need beautifulsoup4 for this (install it with pip install beautifulsoup4):

from django.http import HttpResponse
from bs4 import BeautifulSoup

class CleanCMSClassesMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        
        # Only process HTML responses
        if 'text/html' in response.get('Content-Type', ''):
            soup = BeautifulSoup(response.content, 'html.parser')
            
            # Remove cms-plugin and cms-placeholder classes
            for element in soup.find_all(class_=lambda c: c and ('cms-plugin' in c or 'cms-placeholder' in c)):
                # Filter out unwanted classes and reassign
                new_classes = [cls for cls in element.get('class', []) if not ('cms-plugin' in cls or 'cms-placeholder' in cls)]
                element['class'] = new_classes if new_classes else None
            
            response.content = str(soup).encode(response.charset)
        
        return response

Add this middleware to your settings.MIDDLEWARE list (place it after any middleware that modifies HTML content to ensure it runs last).

4. Frontend JavaScript Cleanup

If you prefer not to touch backend code, you can use JavaScript to remove the classes after the page loads:

document.addEventListener('DOMContentLoaded', () => {
    // Target elements with cms-plugin or cms-placeholder classes
    document.querySelectorAll('[class*="cms-plugin"], [class*="cms-placeholder"]').forEach(el => {
        el.classList.forEach(cls => {
            if (cls.startsWith('cms-plugin') || cls.startsWith('cms-placeholder')) {
                el.classList.remove(cls);
            }
        });
    });
});

This is a quick fix, but note that users with JavaScript disabled will still see the classes.


Configuration & Custom Rendering Support

Django CMS doesn’t have a built-in setting to disable these classes directly, but it fully supports customizing rendering behavior:

  • You can replace default rendering logic by overriding plugin classes (as shown in method 2) or creating custom plugin renderers.
  • For advanced use cases, you can hook into Django CMS’s cms.signals.plugin_rendered signal to modify output HTML before it’s added to the page.

内容的提问来源于Stack Exchange,提问作者NicoR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:05:30