One `\newcommand` for inserting figures differentiating two cases with/without captions
Really I wouldn't use a command at all, it is better to use the enviornment syntax (for example it helps editors to syntax highlight or give context sensitive help if you don't hide the standard syntax)
If you do use a command beware adding extra white space (your definitions add several space tokens).
That said, \newcommand
supports defining commands with an optional argument.
\newcommand{\fig}[3][\relax]{%
\begin{figure}[htp]%
\centering
\includegraphics[#2]{#3}%
\ifx\relax#1\else\caption{#1}\fi
\end{figure}%
}
\fig{width = 0.50\textwidth}{fig/duck.pdf} % for fig without caption
\fig[Zzzzz]{width = 0.50\textwidth}{fig/duck.pdf} % for fig without caption
I don't think you gain too much with this approach. Anyway, here's a possible implementation.
\documentclass{article}
\usepackage{graphicx,xparse}
\ExplSyntaxOn
\NewDocumentCommand{\hfig}{O{}mO{}}
{
\group_begin:
\keys_set:nn { hengxin/fig } { #3 }
\use:x { \exp_not:N \begin{figure}[\l_hengxin_hfig_pos_tl] }
\centering
\includegraphics[#1]{#2}
\tl_if_empty:NF \l_hengxin_hfig_caption_tl
{
\tl_if_empty:NTF \l_hengxin_hfig_shortcaption_tl
{
\caption{\l_hengxin_hfig_caption_tl}
}
{
\caption[\l_hengxin_hfig_shortcaption_tl]{\l_hengxin_hfig_caption_tl}
}
}
\end{figure}
\group_end:
}
\keys_define:nn { hengxin/fig }
{
caption .tl_set:N = \l_hengxin_hfig_caption_tl,
shortcaption .tl_set:N = \l_hengxin_hfig_shortcaption_tl,
pos .tl_set:N = \l_hengxin_hfig_pos_tl,
pos .initial:n = htp,
}
\ExplSyntaxOff
\begin{document}
\hfig[width=.3\textwidth]{example-image-a}
\hfig[width=.3\textwidth]{example-image-b}[
caption=This is a caption\label{aaa},
pos=bp
]
\end{document}
You can also specify a shortcaption
key, for the case \caption[Short]{Long}
.