keep user-generated content from breaking layout?

感情迁移 提交于 2019-12-05 07:47:36
Wesley Murch
  • Maybe overkill, but HTML Tidy could help if you can use it.

  • Use a WYSIWYG like TinyMCE or CKEditor that has built in cleanup methods.

Robert Koritnik's suggestion to use markdown seems brilliant, especially considering that you only allow a few harmless formatting tags.

I don't think there's anything you can do with CSS to stop layouts from breaking due to open HTML tags, so I would probably forget that idea.

Why not use markdown

If your users are HTML literate or people that can grasp the concept of markdown syntax I suggest you rather go with that. Stackoverflow works great with it. I can't imagine having a usual rich editor on Stackoverflow. Markdown editors are much simpler and faster to use and provide enough formatting capabilities for most situations. If you need some special additional features you can always add those in but for starters oute of the box capabilities will suffice.

Real-time view for self validation

But don't forget to include a real time view of what users are writing. Self validation makes miracles so they correct their own mistakes before posting data.

Instead of parsing the result or forcing the user to use a structured format, just display the content within an iframe:

<iframe id="user_html"></iframe>

<script>
document.getElementById("user_html").src = "data:text/html;charset=utf-8," + escape(content);
</script>

I built custom CMS systems exclusively for several years and always had great luck with a combination of a quality WYSIWYG, strong front-end validation, and relentless back-end validation.

I always gravitate toward CKEditor because it's the only front-end editor that can deal with Microsoft Word output on the front end...that's a must-have in my books. Sure, others have a paste from word solution, but good luck getting users to use it. I've actually had a client overload a db insert thanks to Microsoft Word that didn't get scrubbed in Tiny. HTML tidy is a great solution to clean things up prior to validation on the back end.

CK has built-in templates and classes, so I used those to help my users format without going overboard. On the back-end I checked to ensure they hadn't tried any funny business with CSS, but it was never a concern with that group of users. Give them enough (safe) features and they'll never HAVE to go rogue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!