Conditional HTML tag in HAML

无人久伴 提交于 2019-12-03 06:34:27

问题


How would I format HAML to output a style similar to the conditional HTML tags used for cross-browser targeting?

<!doctype html>
<!--[if lt IE 8]> <html class="no-js ie7 oldie" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en"> <![endif]-->
<!--[if IE 9]>    <html class="no-js ie9 oldie" lang="en"> <![endif]-->
<!--[if gt IE 9]><!--> <html class="no-js" lang="en"> <!--<![endif]-->

If I add a conditional, it wraps entire page in the conditional as well. I thought about using HAML's :plain filter at the top and manually adding </html> at the bottom, but this seems less than ideal to me.


回答1:


The first three of these are pretty simple, as they are just plain HTML comments and you can use the Haml support for conditional comments:

/[if lt IE 8] <html class="no-js ie7 oldie" lang="en">
/[if IE 8] <html class="no-js ie8 oldie" lang="en">
/[if IE 9] <html class="no-js ie9 oldie" lang="en">

The last one is a bit different. Breaking it down, what you want is two comments surrounding the html opening tag, so the second comment is the first content of the html element. Also you can’t use the Haml syntax for conditional comments, you’ll have to use a literal comment. In Haml this would look like:

<!--[if gt IE 9]><!-->
%html{:class => 'no-js', :lang => 'en'}
  <!--<![endif]-->

This will produce HTML like this:

<!--[if gt IE 9]><!-->
<html class='no-js' lang='en'>
  <!--<![endif]-->

If you wanted you could use the whitespace removal syntax to make the generated HTML more like your example:

<!--[if gt IE 9]><!-->
%html{:class => 'no-js', :lang => 'en'}<>
  <!--<![endif]-->

Putting it all together:

!!!
/[if lt IE 8] <html class="no-js ie7 oldie" lang="en">
/[if IE 8] <html class="no-js ie8 oldie" lang="en">
/[if IE 9] <html class="no-js ie9 oldie" lang="en">
<!--[if gt IE 9]><!-->
%html{:class => 'no-js', :lang => 'en'}<>
  <!--<![endif]-->
  content here

which produces:

<!DOCTYPE html>
<!--[if lt IE 8]> <html class="no-js ie7 oldie" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]-->
<!--[if IE 9]> <html class="no-js ie9 oldie" lang="en"> <![endif]-->
<!--[if gt IE 9]><!--><html class='no-js' lang='en'><!--<![endif]-->
content here</html>

An alternative technique would be to use Haml’s surround helper:

= surround "<!--[if gt IE 9]><!--><html class='no-js' lang='en'><!--<![endif]-->", "</html>" do
  content here



回答2:


<!doctype html>
/[if lt IE 8] <html class="no-js ie7 oldie" lang="en">
/[if IE 8] <html class="no-js ie8 oldie" lang="en">
/[if IE 9] <html class="no-js ie9 oldie" lang="en">
/ [if gt IE 9]><!
%html.no-js{:lang => "en"}
  / <![endif]


来源:https://stackoverflow.com/questions/12868977/conditional-html-tag-in-haml

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