How to preserve whitespace indentation of text enclosed in HTML
 tags excluding the current indentation level of the 
 tag in the document?

后端 未结 11 1456
萌比男神i
萌比男神i 2020-12-02 18:32

I\'m trying to display my code on a website but I\'m having problems preserving the whitespace indentation correctly.

For instance given the following snippet:

11条回答
  •  时光取名叫无心
    2020-12-02 19:02

    Indenting With Comments

    Since browsers ignore comments, you can use them to indent your pre tag contents.

    Solution

    
      
        
    Here is my code with hack:
    def some_function
      return 'Hello, World!'
    end
          
    Here is my code without hack:
            def some_function
              return 'Hello, World!'
            end
          

    NOTE: a main wrapper was added to provide enough space for the comments.

    Advantages

    • No JavaScript required
    • Can be added statically
    • Minification won't affect the indentation and reduces file size

    Disadvantages

    • Requires a minimum amount of space for the comments
    • Not very elegant unless build tools are used

    Removing Indentation With Node

    A better solution is to remove the leading white-space using either your build process or back-end rendering process. If you are using node.js, then you can use a stream I wrote called predentation. You can use any language you want to build a similar tool.

    Before

    
     
       Here is my code:
       
         def some_function
           return 'Hello, World!'
         end
       

    After

    
     
       Here is my code:
       
    def some_function
      return 'Hello, World!'
    end
       

    Advantages

    • Seamless way to write pre tags
    • Smaller output file size

    Disadvantages

    • Requires a build step in your workflow
    • Does not handle non pre elements with white-space: pre added by CSS

    Removing Indentation With JavaScript

    See this answer to remove indentation with JavaScript

    Advantages

    • Possible to target elements with white-space: pre

    Disadvantages

    • JavaScript can be disabled
    • White-space adds to the file size

提交回复
热议问题