简体   繁体   中英

Django: Dynamic “table of contents” based on HTML tags

I have a model with a TextField that users can populate with HTML. Now I want Django to render a dynamic "Table Of Contents", so that when a <h> tag is used, django automatically adds that to a list. Bonus points if a nested list is also possible.

I've thought about using inclusion tags, but I'm not sure on the exact details. Any help would be much appreciated.

I have never done this exactly...but here is how I would start off.

Get the HTML

First things first - get the user to add the HTML. Possibly install tinyMCE, use tinyMCE's HTML field. The user can copy and paste HTML or add HTML content using tinyMCE's WYSIWUG.

Generate a DOM object

You might be thinking - I will write some regex to find the relevant h1-6 tags. The problem is that parsing html with regex is a nightmare and should not be done with regex .

Next you will probably need to render the html . There are probably quite a few ways to do this.

Table of Contents

Then go through the rendered html and pull out all the h1-6 tags or whatever you are after.

You might want to edit the html and add the TOC to the top of the list - either that or save it as a separate html snippet that you can insert into the main html document when you render it.

If the generating the TOC sounds like too much work...it probably is. I'm sure you could find a solution to automatically pull out the h1 headers and link to the content. Here is a jquery plugin that does just that. A bit of googling could be in order here to find the easiest way to generate the TOC could be in order - seems like it would be quite a common thing.

Other Thoughts

  • Be aware - you need to ensure you aren't parsing javascript when rendering the page due to security implications!
  • Bonus marks for modifying the html to hyperlink the TOC to the actual heading.
  • Make sure you re-generate the TOC if the user modifies HTML content

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM